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