使用Hibernate和注释的复杂主键

时间:2011-05-12 13:09:21

标签: java hibernate jpa annotations

我想为对象生成自定义ID,具体取决于数据库中已存在的值。

我知道有关这个问题的几个问题,但我无法找到解决方案...

这是我的班级:

@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;
}         

我想到了@Formula注释,但我无法让它工作......

提出异常:

java.sql.SQLException: Field 'id' doesn't have a default value 

我不确定@Formula是不是很好的解决方案......

有没有人知道如何让它发挥作用?

非常感谢,

2 个答案:

答案 0 :(得分:1)

试试这个

@Formula(value = "(select t.id+1 from mytable t where t.type=type)") 
private long id;

答案 1 :(得分:0)

我使用@PrePersist注释解决了我的问题。

@PrePersist
private void generateId() {

    if(id>0){
        return;
    }
    id=++type.lastChronoId;
    type.save();
}

将类型修改为Type类,包含最后创建的对象的索引。