How to persist Entity twice JPA - java

I have an entity, that represent order sent by the customer , this order might be updated after some discussion with the customer on phone, but the initial order sent by the customer must be persisted without update.
how i can persist same entity twice , is it efficient to use deep cloning.
i have tried to detach the the entity in order for persistence context to persist a new one , but still the persistence context is updating the first entry.

You can not persist one object twice in one session, so you need copy your order and save (persist) it again.
hibernate copy object values into new object with new generated ID

That's an interesting question. I think the quickest solution would probably be to use a multi-part ID. The first part would be the original order number and then every change increments the second part of the key. In your code you'd just need to find the object, make sure it's detached, alter the second part of the key and then persist it. As long as it's been detached it should then be saved away as a new order.
This post shows you how to use a composite key.

You need to clone/copy the object, ensure it has a unique id (or null if generated).
In EclipseLink there is an API to copy objects,
http://wiki.eclipse.org/EclipseLink/Examples/JPA/AttributeGroup#Copy_Examples

Related

Hazelcast update entities

I want to know if there is a way to let Hazelcast automatically sync the cache with all the updates that an entity receives. here's an example:
I want to update an entity that has been stored into a cache and is also used in other caches. I do a get() and retrieve the value, and then perform an update changing some properties. The problem is that Hazelcast does not automatically serialize the item in the cache after every change, but i need to force a put to actually propagate the update to the cache. And i would need to perform a put for every cache that my entity is stored into. Is there someway to let Hazelcast manage those situations automatically?
#Edit
Just to clarify the problem, here i give you an example:
imagine i have 2 IMaps: map1 stores objects of Entity A, map2 contains object of entity B, and entity B represents a complex object which in turn contains Entity A. If i want to perform an edit on one of the objects contained in map1 (which will be an instance of Entity A), i will do a map1.get(key) and retreive the object. Then i modify this object in some way and i will persist the changes in map1 by doing a map1.put(key, entityA).
The problem rises because in map2, all the entitiesB which contain the jsut modified entityA will not show the update, and i have to manually do a get and a put also in this map.
You can use EntryProcessor to update the content of the entity in the map, directly on the server (without having to perform a get() first). That ways a common update code can be used for all the caches and you save on all network and ser/des overheads too.

Hibernate two versions of the same object

I have an entity that has been loaded from the database in a previous request, that is now modified. It is still detached in the persistence context.
When I'm submitting and entering my save() method, first entityManager.load() gets called to get the previous state of the object, make some comparisons, computations etc. (Im now working with entity and entityBefore)
Saving entity now results in an error. I'm trying to save a different object with the same id.
The solution at the moment is to just detach entityBefore and then use saveOrUpdate. Seemed to work like a charm.
However it only leads to another problem. The entity contains a list of other objects (1-n). Removing one of those from the list returns an error, they've previously been detached aswell.
At the moment I'm not sure what's the best approach to solve this whole thing. How can I manage 2 different versions of the same object, without storing both in the database? Is there a way I can get the old State from the database without modifying the context? Do I need to refresh every object in the list one by one?...
Thanks for any suggestions.

Altering an Object after I Merge it (Persistence Context) breaks update

I have two consecutive operations that need to happen.
First, I insert a new record (I'm using JPA), to use as a historical record, and then I run an update to a record that is always used as the most "current" with information coming in on the call.
The problem is that the object has a composite key, which I need to insert it, but I don't want it returned in the JSON that I return after the update. JPA has a real problem with altering the composite keys, but I found the .detach method which has worked for me in the past. The fields I want to be null are marked as #Transient in the actual object, and no error is thrown. It performs the insert fine, but the update fails if I try to move the primary keys at ALL. Even after the insert is called, and even using the .detach method. Any ideas what I'm missing?
I would think I could do it like so:
em.merge(contract); //Object to be saved
em.detach(contract); // allows me to manipulate it
policy.setContractNum(policy.getId().getContractNum());
policy.setCustNum(policy.getId().getCustNum());
returnPolicyAsList.add(policy);
customer.setPolicies(returnPolicyAsList);
status.setFamCustomer(customer);
status.setStatus(Message.SUCCESS);
status.setStatusMessage(Message.SUCCESS);
return status;
You seem not to quite be in tune with JPA's model of the world. An entity's primary key is its identity. As such, you should never modify the primary key of a persistent entity.
That conflicts a bit with Java's view, which attributes a separate identity to each object. You work with the Java view with entities that are not persistent -- i.e. those that are new, detached, or removed. That's why you can twiddle an entity's PK once you detach it, but you have to understand that doing so changes its identity from JPA's viewpoint. If you later try to merge such an entity then JPA sees only its new identity, not its old one.
If you need to change an entity's PK (generally a bad idea) then you should delete it, change the PK, and then persist it again. On the other hand, if your PK comprises information that may change over time, then you really ought to choose a different PK. Indeed, JPA works most smoothly when you use surrogate PKs instead of PKs comprising business data.

Unique contraint violation whien trying to delete and add a row using Hibernate

I have a project which which has hibernate classes mapped to the underlying tables. There is table which has a composite key.I am deleting the unique row and adding the same row in my hibernate object. Both these objects are part of another object which I am persisting into db. The program throws "UNIQUE CONSTRAINT VIOLATION" error which is presume is because insert is happening before delete operation. Is there way to resolve this using some setting in hibernate or should I have the necessary logic [outside hibernate object manipulation] in place to ensure this does not happen.
You shall ensure that object deletion is flushed to database before you attempt to
create another object with the same key. But in your case it would be better to just replace
data inside of object to be remover with new one. From hibernate point of view, same PC means same object.
When I have used Hibernate in the past, 90% of the time it makes no difference what order you call the insert or delete statement, or even the commit. In most cases, it matters where the session actually closes the Transaction unless you are managing your transaction yourself.
But one great thing about hibernate is that you shouldn't be removing a row that has the same key, you should just update its object instance with the relevant data and persist the update instance. Hibernate will take care of the rest...

What are JPA entities?

I am starting to use JPA and I always get confused with the term of entities and their usage, I have read a lot but I still don't quite get it.
I read the Oracle documentation of it but it does not really explain its role in the transaction.
What are JPA enities? does they actually hold the data for each row, I mean, are they stored instances that hold the row data? or they just map tables of the db and then insert and delete in them?
for example if I use this:
entity.setUserName("michel");
Then persisting it, then changing the user name, and persisitig it again (i.e merging it)
Does this change the previously entered user name? or does it create a new row in the db?
An Entity is roughly the same thing as an instance of a class when you are thinking from a code perspective or a row in a table (basically) when you are thinking from a database perspective.
So, it's essentially a persisted / persistable instance of a class. Changing values on it works just like changing values on any other class instance. The difference is that you can persist those changes and, in general, the current state of the class instance (entity) will overwrite the values the row for that instance (entity) had in the database, based on the primary key in the database matching the "id" or similar field in the class instance (entity).
There are exceptions to this behavior, of course, but this is true in general.
It's a model. It's a domain object that can be persisted. Don't over think it. Akin to a Rails model. And remember, models (in this paradigm) are mutable!

Categories