I want to implement my own strategy for generating primary keys for new rows in my table, for example I want that the id of a host will 172.24.85.20 will be 8520.
Can I somehow extend @GeneratedValue annotation? which approach will you recommend?
I want to implement my own strategy for generating primary keys for new rows in my table, for example I want that the id of a host will 172.24.85.20 will be 8520.
Can I somehow extend @GeneratedValue annotation? which approach will you recommend?
In my projects I'm also using a custom key, because i need entities with a unique identity already before persist() was called. My solution is not using the @GeneratedValue annotation, but initialize the id-field manually. The @GeneratedValue annotation depends on your database and the primary key is provider by it. In your case the id field could be calculated and set before calling EntityManager.persist() or that step can be handled in a @PrePersist annotated EntityListener method (http://www.java2s.com/Tutorial/Java/0355__JPA/EntityListenerPreUpdate.htm). Apart from that extending annotations is not possible (Why is not possible to extend annotations in Java?); you could only combine annotations by using stereotypes or create your own annotations.
You should check this link:
http://blog.anorakgirl.co.uk/2009/01/custom-hibernate-sequence-generator-for-id-field/
You must create a class which implements IdentifierGenerator:
public class StockCodeGenerator implements IdentifierGenerator {
private static Logger log = Logger.getLogger(StockCodeGenerator.class);
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
// Here goes the id generation code
}
}
An then use it in your @GenericGenerator
annotation:
@Id
@GenericGenerator(name="seq_id", strategy="my.package.StockCodeGenerator")
@GeneratedValue(generator="seq_id")
String myColumn;
You may try this one with Date and Calender
public class StockCodeGenerator implements IdentifierGenerator {
private static Logger log = Logger.getLogger(StockCodeGenerator.class);
public StockCodeGenerator() {}
public int generateCustId() {
Random random = new Random();
return random.nextInt(100);
}
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
String prefix = "Custom_String";
Connection connection = session.connection();
System.out.println(session.connection());
Date date = new Date();
Calendar calendar = Calendar.getInstance();
return prefix + "_" + generateCustId() + "_" + calendar.get(1);
}
}
And then use it in your @GenericGenerator annotation:
@Id
@GenericGenerator(name="seq_id",strategy="com.mvc.StockCodeGenerator.
StockCodeGenerator")
@GeneratedValue(generator="seq_id")