Reputation: 111
In JPA, I am using @GeneratedValue:
@TableGenerator(name = "idGenerator", table = "generator", pkColumnName = "Indecator" , valueColumnName = "value", pkColumnValue = "man")
@Entity
@Table(name="Man")
public class Man implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "idGenerator")
@Column(name="ID")
private long id;
public void setId(Long i) {
this.id=i;
}
public Long getId(){
return id;
}
}
I initially set the ID to some arbitrary value (used as a test condition later on):
public class Sear {
public static void main(String[] args) throws Exception {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testID");
EntityManager em = emf.createEntityManager();
Man man = new Man();
man.setId(-1L);
try {
em.getTransaction().begin();
em.persist(man);
em.getTransaction().commit();
} catch (Exception e) { }
if(man.getId() == -1);
}
}
}
What is the expected value of man.id after executing commit()? Should it be (-1), a newly generated value, or I should expect an exception?
I want to use that check to detect any exceptions while persisting.
Upvotes: 1
Views: 6553
Reputation: 18379
In EclipseLink this is configurable using the IdValidation enum and the @PrimaryKey annotation or the "eclipselink.id-validation" persistence unit property.
By default null and 0 will cause the id to be regenerated, but other values will be used. If you set the IdValidation to NEGATIVE, then negative numbers will also be replaced.
You can also configure your Sequence object to always replace the value.
Upvotes: 0
Reputation: 570295
What is the expected value of man.id after executing commit()? Should it be (-1), a newly generated value, or I should expect an exception?
You are just not supposed to set the id
when using GeneratedValue
. Behavior on persist will differ from one implementation to another and relying on this behavior is thus a bad idea (non portable).
I want to use that check to detect any exceptions while persisting.
JPA will throw a (subclass of) PersistenceException
if a problem occurs. The right way to handle a problem would be to catch this exception (this is a RuntimeExeption
by the way).
If you insist with a poor man check, don't assign the id
and check if you still have the default value after persist (in your case, it would be 0L
).
Upvotes: 4
Reputation: 15577
You setting the value of a field that is auto-generated is irrelevant. It will be (should be) set by the JPA implementation according to the strategy specified.
Upvotes: 1