Basically, i want to make a JPA-persisted field in my Entity behave like it is transient on manual serialization
i have a basic class like this:
@Entity
public class Foo implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
long id;
String field;
get/set field;
}
On serialization the id is serialized too. When i Deserialize this class and persist it, it still has the same ID and is (after merging with JPA) the same instance in the database. While this is probably the intended behaviour, i want the deserialized object to be a new object in the database on deserialization.
I tried to make the id transient, but this messes up JPA. The second thing i tried was setting the id to null after deserialization. After that, persisting works. But This gets rather tedious with many different Entities and i get back to my original Question.
Is there an easier way than that? overriding the readObject(...)
method and setting the id to null doesn't work either since JPA uses those methods too.
I would recommend nulling out the id when you want a new object. Making it transient seems like a bad idea, what if you need to serialize the real object at some point.
If you are using EclipseLink, it also offers a copy() API that can clone an object and null the id,
http://wiki.eclipse.org/EclipseLink/Examples/JPA/AttributeGroup#Copy_Examples