@EmbeddedId 和使用 @GenerateValue 自动生成的 id,这种组合不能按需要工作

2024-03-30

我正在尝试使用@EmbeddedId,这是我的代码,如下所示,

create table TBL_EMPLOYEE_002(
  ID integer generated always as identity (start with 100,increment by 10), 
  COUNTRY varchar(50),
  NAME varchar(50),
  constraint PK_EMP_00240 primary key(ID,COUNTRY)
)

嵌入式类如下,

@Embeddable
public class EmployeeIdTwo implements Serializable{
     public EmployeeIdTwo(){}
    public EmployeeIdTwo(String country){
        this.empCountry = country;
    }

    @GeneratedValue(strategy=GenerationType.IDENTITY)
     @Column(name="ID") 
    private Integer employeeId;

    @Column(name="COUNTRY",length=50)
    private String empCountry;

// implementation of hashCode and equals and only getters 
...
}

员工实体如下,

@Entity
@Table(name="TBL_EMPLOYEE_002")
public class EmployeeEntitySix implements Serializable{

    public EmployeeEntitySix(){}
    public EmployeeEntitySix(EmployeeIdTwo id,String name){
        this.id = id;
        this.employeeName = name;
    }

    @EmbeddedId    
    private EmployeeIdTwo id;

    @Column(name="NAME")
    private String employeeName;

// getters and setters
}

这是在main方法中编写的代码,

private static void storVal(EntityManager em){
    EmployeeEntitySix employee = new EmployeeEntitySix(new EmployeeIdTwo("KENYA"), "Henry Olaanga");
    em.persist(employee);
}

但是一旦我运行上面的代码,我就会得到一个异常,如下所示,

Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Attempt to modify an identity column 'ID'. 

你能告诉我我错在哪里吗 如果我的 EmbeddedId 类包含自动生成的列,那么应该采用什么方法。

只是知道我使用 hibernate 作为持久性提供程序,使用 JPA 作为持久性 API


我假设你不会问这个问题,如果Id可以轻松且唯一地识别员工。如果您有能力修改表格,我建议您要么制作Id可靠地唯一,或者添加自动生成的UniqueId column.

其中一些错误实际上来自数据库模式,而不是来自 JPA/Hibernate。如果您尝试更新数据库没有生成策略的列,这可能是导致错误的原因。

您可能还可以看看自动增量 id 未反映在使用 JPA 的复合键中 https://stackoverflow.com/questions/4813755/autoincrement-id-is-not-reflecting-in-composite-key-using-jpa,因为我认为这涵盖了您所问的问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

@EmbeddedId 和使用 @GenerateValue 自动生成的 id,这种组合不能按需要工作 的相关文章

随机推荐