如何在Hibernate中的复合主键中自动增加ID? [英] How to autoincrement an Id in a composite primary key in Hibernate?
本文介绍了如何在Hibernate中的复合主键中自动增加ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有复合主键的表- groupId 和 batchId .实体类如下:
I have a table with a composite primary key - groupId and batchId. Entity class looks like:
@Entity(name="EMPLOYEE")
public class Employee {
@EmbeddedId
private EmployeePK employeePK;
//Other columns and their getters and setters
//Getters and setters
}
复合PK:
@Embeddable
public class EmployeePK implements Serializable {
private long groupId;
private long batchId;
@GeneratedValue(strategy=GenerationType.AUTO)
public long getBatchId() {
return batchId;
}
public void setBatchId(long batchId) {
this.batchId = batchId;
}
}
我正在尝试自动增加批次ID,以便插入新记录.
I'm trying to auto increment the batch Id, for a new record to be inserted.
//For saving
Employee employee = new Employee();
EmployeePK pk = new IRAmendmentBatchesPK();
pk.setBatchId(0);
pk.setGroupId(4388);
Employee employee = employeeRepository.save(employee);
//Repository Interface
public interface EmployeeRepository extends JpaRepository<Employee, EmployeePK>{
}
我明确地将 batchId 设置为0,希望在保存(插入)期间在batchId中设置自动递增的值.到目前为止,此代码将保存一个新的条目,其batchId为0.
I'm explicity setting batchId as 0, in hopes that the auto-incremented value is set in the batchId during save(insert). As of now, this code will save a new entry with batchId as 0.
推荐答案
@Embeddable
public class EmployeePK implements Serializable {
private long groupId;
@GeneratedValue(strategy = GenerationType.AUTO)
private long batchId;
public long getBatchId() {
return batchId;
}
public void setBatchId(long batchId) {
this.batchId = batchId;
}
//implements equals and hashcode
}
这篇关于如何在Hibernate中的复合主键中自动增加ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文