这是我的sql表结构:
create table TBL_EMPLOYEE_FIVE(
EMP_ID integer generated always as identity(start with 50, increment by 4),
NAME varchar(50),
COUNTRY varchar(50),
MGR_ID integer,
MGR_COUNTRY varchar(50),
constraint PK_COMPOSIT_001AD primary key(EMP_ID,COUNTRY),
constraint FK_COMPO_00123 foreign key(MGR_ID,MGR_COUNTRY) references TBL_EMPLOYEE_FIVE
)
这是我的实体映射:
@Entity
@Table(name="TBL_EMPLOYEE_FIVE")
@IdClass(EmployeeId.class)
public class EmployeeOne implements Serializable{
public EmployeeOne(){}
public EmployeeOne(String employeeName,String empCountry){
this.empCountry = empCountry;
this.employeeName = employeeName;
}
public EmployeeOne(String employeeName,String empCountry,EmployeeOne manager){
this.empCountry = empCountry;
this.employeeName = employeeName;
this.manager = manager;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="EMP_ID")
private Integer employeeId;
@Id
@Column(name="COUNTRY")
private String empCountry;
@Column(name="NAME")
private String employeeName;
@ManyToOne( cascade= {CascadeType.PERSIST, CascadeType.PERSIST},
fetch= FetchType.LAZY,
targetEntity=EmployeeOne.class)
@JoinColumns({
@JoinColumn(name="MGR_ID",referencedColumnName="EMP_ID"),
@JoinColumn(name="MGR_COUNTRY",referencedColumnName="COUNTRY")
})
private EmployeeOne manager;
@OneToMany(cascade={CascadeType.PERSIST, CascadeType.PERSIST},mappedBy="manager")
private Set<EmployeeOne> employees;
// getters and setters,
}
这是嵌入式id映射,
@Embeddable
public class EmployeeId implements Serializable{
public EmployeeId(){}
public EmployeeId(Integer employeeId,String empCountry){
this.employeeId = employeeId;
this.empCountry = empCountry;
}
@Column(name="EMP_ID")
private Integer employeeId;
@Column(name="COUNTRY")
private String empCountry;
// only getters and implementation of hashcode and equals method
}
这就是我试图在我的主要方法中运行的内容:
EmployeeOne manager = new EmployeeOne("Yousuf Ahmadinejad", "IRAN");
em.persist(manager);
但在这里,我得到一个例外,即
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Attempt to modify an identity column 'EMP_ID'.
这不像我没有理解异常,
但为什么这个例外发生在第一位?我已经使用@GenerateValue为Empid注释了它,我没有手动设置empId。是否发生此异常是因为我将主键组合为empId和country,而empId是使用Identity自动生成的,因此它给出了异常?
你能告诉我哪里出错了
我想在这里添加的另一件事是,如果我删除了EmployeeId.java的@Column和@Embeddeble注释,而不是运行,我会得到以下异常,
Caused by: org.hibernate.PropertyAccessException: could not set a field value by reflection setter of com.entities.derived.EmployeeId.employeeId
所以只是试图找到解决方案来坚持员工保持自动生成的ID,因为它是
答案 0 :(得分:0)
首先,Hibernate不为复合键生成id,因此您应该将EmployeeOne更改为:
@Id
//@GeneratedValue(strategy=GenerationType.IDENTITY) remove this line
@Column(name="EMP_ID")
private Integer employeeId;
其次,不是你应该如何实现EmployeeId
复合密钥类。请参阅:https://stackoverflow.com/a/3588400/1981720
第三,数据库抛出异常,而不是Hibernate。检查您是否与另一个数据库获得了相同的异常。