JPA Null or zero primary key encountered in unit of work clone
This happend to me because I manually added an entry to my database with the id 0 (zero).In my case EclipseLink "couldn't" handle an id with zero.So I added following to my persistence.xml:
<property name="eclipselink.allow-zero-id" value="true"/>
This property says EclipseLink to handle zero as a valid id.
You need to annotate your id field with @GeneratedValue, in order for JPA to know that the DB will generate the id automatically:
@Id@Basic(optional = false)@Column(name = "A_ID")@SequenceGenerator( name = "mySeq", sequenceName = "MY_SEQ", allocationSize = 1, initialValue = 1 )@GeneratedValue(strategy=GenerationType.IDENTITY, generator="mySeq")private BigDecimal aId;
With oracle you can use
@SequenceGenerator in which case you don't need a trigger to query the sequence and populate the ID, JPA will do it for you. I'm not sure if
GenerationType.AUTO will work with oracle but if it does, you'd need a trigger to query the sequence and populate the id.
GenerationType.TABLE is the most portable solution, since you use an independent table managed by JPA to store the sequence, it works across all databases.
Check the docs in the link above.
As you said, the problem lies in the fact that even when you commit a transaction, the Auto-increment function isn't invoked right away. Actually, while you are managing database interactions with the same EntityManager it won't.My question would rather be: why are you persisting, then committing the transaction if you flush it anyway? Looks like duplicated code to me.See this on flush.