When I use em.persist() to insert a new instance of an entity-class, generated id is reflected in entity-class, but the version property still shows null, it is not reflected in the entity-class.
I’m using GlassFish 3.1.1.
partial entity-class code
@Id
@GeneratedValue
private Long id;
@Version
private Long version;
public void create(Item item) {
System.out.println("Before Creating " + item.id + ", " + item.version);
entityManager.persist(item);
System.out.println("After Creating " + item.id + ", " + item.version);
}
Statement after persist() displays item.id shows 1, but item.version shows null, even though, if I check in database it is 1.
Is it supposed to be this way, or is a bug?
persist()doesn’t insert the entity in database. And you’re not even guaranteed to have an ID assigned afterpersist()has been called.What persist does is to make a transient entity attached to the entity manager. At flush time, the version will be assigned.
So, if you really need the new version before the transaction is committed, call
flush()explicitely and then get the new version. But usually, it’s not needed because you don’t need to deal with the version field yourself, so just commit the transaction: it will cause a flush to be done, and the version will thus be assigned.