【问题标题】:Complex Primary Key using Hibernate with Annotation使用带有注释的 Hibernate 的复杂主键
【发布时间】:2011-05-12 13:09:21
【问题描述】:

我想根据数据库中已有的值为对象生成自定义 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: 字段 'id' 没有默认值 

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

有人知道我如何使它工作吗?

非常感谢,

【问题讨论】:

    标签: java hibernate jpa annotations


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 这修复了异常引发,但实际上我误解了这个注释的用法:我的“id”字段不再是表格列......
    【解决方案2】:

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

    @PrePersist
    private void generateId() {
    
        if(id>0){
            return;
        }
        id=++type.lastChronoId;
        type.save();
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 2015-07-07
      相关资源
      最近更新 更多