Reputation: 5646
I am having a requirement where if the user enters value for the primary key, then I need to use that when creating an entity and if in case the user does not provide value, the primary key needs to be auto-generated like R00001, R0002 etc.I would like to know how I could achieve this and any guidance on that
Upvotes: 1
Views: 435
Reputation: 26572
Try to take advantage of the IdentifierGenerator
interface and define an implementation of your own.
public class MyEntityIdGenerator implements IdentifierGenerator{
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
MyEntity entity = (MyEntity)object;
if(entity.getId()==null){
Connection con = session.connection();
// retrieve next sequence val from database for example
return nextSeqValue;
}
}
}
Then add appropriate annotations on the id field in your entity:
@Id
@GenericGenerator(name="myCustomGen", strategy="com.example.MyEntityGenerator")
@GeneratedValue(generator="myCustomGen")
Upvotes: 1