Jpa 2.0 eclipselink how to persist(insert) entity class, without auto generated primary key - jpa-2.0

I user JPA 2.0 with eclipselink with postgres DB.
I want to presist new entity Class. The primary key is an Integer, with not null constraint.
When i one to insert, JPA don't know the value of the new Primary key.
How can i get the new primary key value?
I can't change the DB sheme.
I think about get max id and insert a greater one to the DB, but it kind of messy solution.
This is the definition of the primary key in the entity class, generated with netBeans 7.0.1:
#Id
#Basic(optional = false)
#Column(name = "obj_id")
private Integer ObjId;
public void save(){
TkTopoVerzio test= new TkTest();
// set all the value
// ....
try {
em.getTransaction().begin();
em.persist(test);
em.getTransaction().commit();
} catch(javax.persistence.NoResultException ex){
//Todo : manage exception
} catch (Exception ex){
// toDO : manage exception
}
}

If this is an existing app, how does it assign primary keys?
You can of course assign the pk in your new objects directly before calling persist, but EclipseLink also allows custom pk generators:
http://wiki.eclipse.org/EclipseLink/Examples/JPA/CustomSequencing
which would allow you to assign a pk using what ever strategy you need.
The problem with what you are suggesting (using max to find existing values) is that this very difficult to be thread or even multi-app safe. A highly concurrent or distributed app may run into problems with pk reuse. UUID might be a better way to go if you cannot use a database oriented pk generation strategy. A good resource is here:
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Advanced_Sequencing

Related

Save entity to Datastore and return it so that any further queries to the same entity are guaranteed to reflect the new updates

I want to load an entity by key, update it, save it back to Datastore and then return it to the client from an endpoint. However, I want to make absolutely sure that when I return the entity to the client, the updated entity has been saved and propagated across the datastore. This way, if the client queries for that entity with another endpoint immediately after, the updated one will return.
Using Objectify, this is what I have so far:
First I load the entity, update some values and then load it again by the entity key and return it. Will this second load and return of the entity be strongly consistent and reflect the new value?
// Load the entity by key
Key<Thing> thingKey = Key.create(Thing.class, id);
Thing thing = ofy().load().key(thingKey).now();
// Update some values
thing.setSomeProperty("new value");
// Save entity
ofy().save().entity(thing);
// Load entity by key - will this loaded entity be guaranteed to reflect the above update?
return ofy().load().key(thingKey).now();
Note: I do not want to return the local entity I set the new values to because I do not want the client to potentially query for the entity with the new updates and not get it because they haven't been committed yet due to eventual consistency.
Could this below be another option to achieve the same effect?
// Load the entity by key
Key<Thing> thingKey = Key.create(Thing.class, id);
Thing thing = ofy().load().key(thingKey).now();
// Update some values
thing.setSomeProperty("new value");
// Will this save wait until the entity is saved/propagated across the datastore and thus any queries to this entity after this statement will reflect the new update?
ofy().save().entity(thing).now();
// Just return the entity we updated
return thing
There is no difference between those two sequences. The last load() simply loads the same object out of the session cache. You might as well just return the object.
Keep in mind that you need to run this inside a transaction to be safe. Otherwise you run the risk that some other conflicting write will get overwritten and therefore lost between the load and the save.
return ofy().transact(() -> {
Key<Thing> thingKey = Key.create(Thing.class, id);
Thing thing = ofy().load().key(thingKey).now();
thing.setSomeProperty("new value");
ofy().save().entity(thing).now();
return thing;
}
BTW with Firestore, eventual consistency really isn't a thing anymore. But that doesn't mean that data won't necessarily be stale. Technically any piece of data can be stale the moment after it is fetched from the datastore. A transaction ensures a consistent view of the data (ie, all transactions are serializable so data will not be lost).

Google Cloud Datastore - get after insert in one request

I am trying to retrieve an entity immediately after it was saved. When debugging, I insert the entity, and check entities in google cloud console, I see it was created.
Key key = datastore.put(fullEntity)
After that, I continue with getting the entity with
datastore.get(key)
, but nothing is returned. How do I retrieve the saved entity within one request?
I've read this question Missing entities after insertion in Google Cloud DataStore
but I am only saving 1 entity, not tens of thousands like in that question
I am using Java 11 and google datastore (com.google.cloud.datastore. package)*
edit: added code how entity was created
public Key create.... {
// creating the entity inside a method
Transaction txn = this.datastore.newTransaction();
this.datastore = DatastoreOptions.getDefaultInstance().getService();
Builder<IncompleteKey> builder = newBuilder(entitykey);
setLongOrNull(builder, "price", purchase.getPrice());
setTimestampOrNull(builder, "validFrom", of(purchase.getValidFrom()));
setStringOrNull(builder, "invoiceNumber", purchase.getInvoiceNumber());
setBooleanOrNull(builder, "paidByCard", purchase.getPaidByCard());
newPurchase = entityToObject(this.datastore.put(builder.build()));
if (newPurchase != null && purchase.getItems() != null && purchase.getItems().size() > 0) {
for (Item item : purchase.getItems()) {
newPurchase.getItems().add(this.itemDao.save(item, newPurchase));
}
}
txn.commit();
return newPurchase.getKey();
}
after that, I am trying to retrieve the created entity
Key key = create(...);
Entity e = datastore.get(key)
I believe that there are a few issues with your code, but since we are unable to see the logic behind many of your methods, here comes my guess.
First of all, as you can see on the documentation, it's possible to save and retrieve an entity on the same code, so this is not a problem.
It seems like you are using a transaction which is right to perform multiple operations in a single action, but it doesn't seem like you are using it properly. This is because you only instantiate it and close it, but you don't put any operation on it. Furthermore, you are using this.datastore to save to the database, which completely neglects the transaction.
So you either save the object when it has all of its items already added or you create a transaction to save all the entities at once.
And I believe you should use the entityKey in order to fetch the added purchase afterwards, but don't mix it.
Also you are creating the Transaction object from this.datastore before instantiating the latter, but I assume this is a copy-paste error.
Since you're creating a transaction for this operation, the entity put should happen inside the transaction:
txn.put(builder.builder());
Also, the operations inside the loop where you add the purchase.getItems() to the newPurchase object should also be done in the context of the same transaction.
Let me know if this resolves the issue.
Cheers!

Doctrine2 entity default value for ManyToOne relation property

I've got a Doctrine2 Entity called "Order", which has several status properties. The allowed status' are stored in a different Entity, so there is a ManyToOne relation defined for those entities.
/**
* #ORM\Entity()
*/
class Order extends AbstractEntity {
// ...
/**
* #ORM\ManyToOne(targetEntity="Status")
* #ORM\JoinColumn(onDelete="NO ACTION", nullable=false)
*/
protected $status;
/** #ORM\Column(nullable=true) */
protected $stringProperty = "default value";
}
I need to set this status property to a default value when creating a new instance of the order object.
For a "non-relation" property I can simply set it like the $stringProperty above. But how to do it for relations?
I cannot set the value to the id of the related record, as Doctrine2 will complain.
It's fine if the configured default is a "Reference" to the status entity. The available status' are fixed and won't change (often).
How do I configure the entity to have a proper default relation configured.
Preferably not in a listener when persisting, as the status may be requested before that.
There are several approaches but I would suggest using the OrderRepository as a factory for creating new orders.
class OrderRepository
{
public function create()
{
$order = new Order();
$status = $this->_em->find('Status','default'); // or getReference
$order->setStatus($status);
return $order;
}
}
// In a controller
$orderRepository = $this->container->get('order_repository');
$order = $orderRepository->create();
By going with a repository you can initialize complex entity graphs that will be ready for persisting.
==========================================================================
Plan B would be to do this sort of thing within the order object and then use listeners to "fix things up" before persisting or updating.
class Order
{
public function __construct()
{
$this->status = new Status('Default');
}
}
The problem of course is that a default status object already exists in the database so when you flush you will get a error. So you need to hang an onFlush(http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#onflush) listener on the entity manager, check to see if the status object is being managed by the entity manager and, if not, replace it with a managed object fetched via the entity manager.
This approach lets you deal with more "pure" domain models without worrying as much about the persistence layer. On the other hand, dealing with the flush can be tricky. On the gripping hand, once you get it working then it does open up some major possibilities.
========================================================
There is also the question of what exactly the status entity does. If all it contains is some sort of status state ('entered',processed') etc. Then you might consider just having it be a string. Sort of like the ROLE_USER objects.

How to manually set a primary key in Doctrine2

I am importing data into a new Symfony2 project using Doctrine2 ORM.
All new records should have an auto-generated primary key. However, for my import, I would like to preserve the existing primary keys.
I am using this as my Entity configuration:
type: entity
id:
id:
type: integer
generator: { strategy: AUTO }
I have also created a setter for the id field in my entity class.
However, when I persist and flush this entity to the database, the key I manually set is not preserved.
What is the best workaround or solution for this?
The following answer is not mine but OP's, which was posted in the question. I've moved it into this community wiki answer.
I stored a reference to the Connection object and used that to manually insert rows and update relations. This avoids the persister and identity generators altogether. It is also possible to use the Connection to wrap all of this work in a transaction.
Once you have executed the insert statements, you may then update the relations.
This is a good solution because it avoids any potential problems you may experience when swapping out your configuration on a live server.
In your init function:
// Get the Connection
$this->connection = $this->getContainer()->get('doctrine')->getEntityManager()->getConnection();
In your main body:
// Loop over my array of old data adding records
$this->connection->beginTransaction();
foreach(array_slice($records, 1) as $record)
{
$this->addRecord($records[0], $record);
}
try
{
$this->connection->commit();
}
catch(Exception $e)
{
$output->writeln($e->getMessage());
$this->connection->rollBack();
exit(1);
}
Create this function:
// Add a record to the database using Connection
protected function addRecord($columns, $oldRecord)
{
// Insert data into Record table
$record = array();
foreach($columns as $key => $column)
{
$record[$column] = $oldRecord[$key];
}
$record['id'] = $record['rkey'];
// Insert the data
$this->connection->insert('Record', $record);
}
You've likely already considered this, but my approach would be to set the generator strategy to 'none' for the import so you can manually import the existing id's in your client code. Then once the import is complete, change the generator strategy back to 'auto' to let the RDBMS take over from there. A conditional can determine whether the id setter is invoked. Good luck - let us know what you end up deciding to use.

How should I do post persist/update actions in doctrine 2.1, that involves re-saving to the db?

Using doctrine 2.1 (and zend framework 1.11, not that it matters for this matter), how can I do post persist and post update actions, that involves re-saving to the db?
For example, creating a unique token based on the just generated primary key' id, or generating a thumbnail for an uploaded image (which actually doesn't require re-saving to the db, but still) ?
EDIT - let's explain, shall we ?
The above is actually a question regarding two scenarios. Both scenarios relate to the following state:
Let's say I have a User entity. When the object is flushed after it has been marked to be persisted, it'll have the normal auto-generated id of mysql - meaning running numbers normally beginning at 1, 2, 3, etc..
Each user can upload an image - which he will be able to use in the application - which will have a record in the db as well. So I have another entity called Image. Each Image entity also has an auto-generated id - same methodology as the user id.
Now - here is the scenarios:
When a user uploads an image, I want to generate a thumbnail for that image right after it is saved to the db. This should happen for every new or updated image.
Since we're trying to stay smart, I don't want the code to generate the thumbnail to be written like this:
$image = new Image();
...
$entityManager->persist($image);
$entityManager->flush();
callToFunctionThatGeneratesThumbnailOnImage($image);
but rather I want it to occur automatically on the persisting of the object (well, flush of the persisted object), like the prePersist or preUpdate methods.
Since the user uploaded an image, he get's a link to it. It will probably look something like: http://www.mysite.com/showImage?id=[IMAGEID].
This allows anyone to just change the imageid in this link, and see other user's images.
So in order to prevent such a thing, I want to generate a unique token for every image. Since it doesn't really need to be sophisticated, I thought about using the md5 value of the image id, with some salt.
But for that, I need to have the id of that image - which I'll only have after flushing the persisted object - then generate the md5, and then saving it again to the db.
Understand that the links for the images are supposed to be publicly accessible so I can't just allow an authenticated user to view them by some kind of permission rules.
You probably know already about Doctrine events. What you could do:
Use the postPersist event handler. That one occurs after the DB insert, so the auto generated ids are available.
The EventManager class can help you with this:
class MyEventListener
{
public function postPersist(LifecycleEventArgs $eventArgs)
{
// in a listener you have the entity instance and the
// EntityManager available via the event arguments
$entity = $eventArgs->getEntity();
$em = $eventArgs->getEntityManager();
if ($entity instanceof User) {
// do some stuff
}
}
}
$eventManager = $em->getEventManager():
$eventManager->addEventListener(Events::postPersist, new MyEventListener());
Be sure to check e. g. if the User already has an Image, otherwise if you call flush in the event listener, you might be caught in an endless loop.
Of course you could also make your User class aware of that image creation operation with an inline postPersist eventHandler and add #HasLifecycleCallbacks in your mapping and then always flush at the end of the request e. g. in a shutdown function, but in my opinion this kind of stuff belongs in a separate listener. YMMV.
If you need the entity id before flushing, just after creating the object, another approach is to generate the ids for the entities within your application, e. g. using uuids.
Now you can do something like:
class Entity {
public function __construct()
{
$this->id = uuid_create();
}
}
Now you have an id already set when you just do:
$e = new Entity();
And you only need to call EntityManager::flush at the end of the request
In the end, I listened to #Arms who commented on the question.
I started using a service layer for doing such things.
So now, I have a method in the service layer which creates the Image entity. After it calls the persist and flush, it calls the method that generates the thumbnail.
The Service Layer pattern is a good solution for such things.