I have a new object. I want to know id before saving it. Is it possible? Or there is another way for this? I am using jpa as orm and oracle as database.
@Id
@Basic(optional = false)
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "woTypeSeq")
private Long id;
I have a code field in my entity. If the user doesn’t enter a value for the code field, I want to set code as entity’s id. If I persist entity, of course i can get id and set code value as id, but this is extra query database.
I want to do something like that
if(entity.getCode()==null) {
entity.setCode(entity.getId);
jpaDao.saveOrUpdate(entity);
}
After long researching about this, finally I found a solution.
In fact, if you use sequence generator in jpa, certainly you cannot obtain entity’s id before saving it in database, because next id will be assigned by database sequence.
There is one way to obtain the id if you use a custom generator, you can get the id before saving. Here is simple implementation:
Using CustomGenerator for id field: