这是我的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 和国家/地区,并且 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 不变