Java Persistence/Identity and Sequencing

Java Persistence/Identity and Sequencing

 

Common Problems

null is inserted into the database, or error on insert.
This typically occurs because the @Id was not configured to use an @GeneratedValue(strategy="IDENTITY"). Ensure it is configured correctly. It could also be that your JPA provider does not support identity sequencing on the database platform that you are using, or you have not configured your database platform. Most providers require that you set the database platform through a persistence.xml property, most provider also allow you to customize your own platform if it is not directly supported. It may also be that you did not set your primary key column in your table to be an identity type.

 Object's id is not assign after persist.
Identity sequencing requires the insert to occur before the id can be assigned, so it is not assigned on persist like other types of sequencing. You must either call commit() on the current transaction, or call flush() on the EntityManager. It may also be that you did not set your primary key column in your table to be an identity type.

Child's id is not assign from parent on persist.
A common issue is that the generated Id is part of a child object's Id through a OneToOne or ManyToOne mapping. In this case, because JPA requires that the child define a duplicate Basic mapping for the Id, its Id will be inserted as null. One solution to this is to mark the Column on the Id mapping in the child as insertable=false, updateable=false, and define the OneToOne or ManyToOne using a normal JoinColumn this will ensure the foreign key field is populated by the OneToOne or ManyToOne not the Basic. Another option is to first persist the parent, then call flush() before persisting the child.

Poor insert performance.
Identity sequencing does not support sequence preallocation, so requires a select after each insert, in some cases doubling the insert cost. Consider using a sequence table, or sequence object to allow sequence preallocation.

你可能感兴趣的:(JPA)