3

我正在尝试使用@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)
)

Embedded类如下,

@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 类包含自动生成的列,您能否让我知道我哪里出错了,而不是应该采用什么方法。

只是要知道我使用休眠作为持久性提供者和 JPA 作为持久性 API

4

1 回答 1

0

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

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

您可能还会查看autoincrement id is not reflect in composite key using JPA,因为我认为这涵盖了您所询问的内容。

于 2013-04-02T04:04:59.940 回答