java - 使用带注释的 Hibernate 的复杂主键

标签 java hibernate jpa annotations

我想根据数据库中已有的值为对象生成自定义 ID。

我知道有人问了几个关于那个主题的问题,但我想不出一个解决方案...

这是我的类(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;
}         

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

引发异常:

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

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

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

非常感谢,

最佳答案

试试这个

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

关于java - 使用带注释的 Hibernate 的复杂主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5978466/

相关文章:

java - @Valid 注解不验证子对象列表

Java : Iterating a Set in ibatis

java - 使用 java 在 selenium 中设置 owasp zap 驱动程序

java - c3p0属性在配置文件中的哪里放置?

java - 如何用JPA注解Map<Entity,INTEGER>?

java - JPA:单向多对一和级联删除

java - ClassCastException :java. lang.Class 无法转换为 java.lang.reflect.ParameterizedType

java - hibernate MaterializedClobType 存储长对象而不是文本

java - Eclipselink @mapkey 和 @JoinFetch(JoinFetchType.OUTER) 不能共存?

java - 我是 Spring Boot 新手,试图了解 Hibernate 映射,下面是我的代码