Reputation: 161
I would like to generate a custom ID for an object, depending on values already in database.
I know several questions were asked on that subject, but I can't figure a solution out...
Here is my class :
@Entity
class A {
// primary key for table
@GeneratedValue
@Id
private long tableId;
// id -> should be generated as (1+ (max id of type 'type'))
@Formula("1+(select t.id from mytable t where t.type=type)")
private long id;
// type
private String type;
}
I thought of the @Formula annotation, but I can't get it work...
exception raised :
java.sql.SQLException: Field 'id' doesn't have a default value
I'm not sure the @Formula
is the good solution...
Does anybody has a clue of how I can make it work ?
Thanks a lot,
Ben
Upvotes: 2
Views: 856
Reputation: 161
I solved my problem using a @PrePersist annotation.
@PrePersist
private void generateId() {
if(id>0){
return;
}
id=++type.lastChronoId;
type.save();
}
with type modified to a Type class, containing the index of the last created object.
Upvotes: 0
Reputation: 16037
try this
@Formula(value = "(select t.id+1 from mytable t where t.type=type)")
private long id;
Upvotes: 1