gpt4 book ai didi

java - 使用entityManager将多条记录插入到包含@GenerateValue的表中

转载 作者:行者123 更新时间:2023-12-02 10:00:59 27 4
gpt4 key购买 nike

我是 hibernate 新手,我一直面临着将数据插入具有自动生成 ID 列的 SAMPLE 表的任务。

我正在使用 EntityManager 对象将对象持久保存到数据库中,但是出现错误:

IllegalArgumentException in class: SamplePk, setter method of property: id_sample

Expected type: java.lang.Integer, actual value: org.hibernate.id.IdentifierGeneratorHelper$2

请在下面找到我的代码

Entity Class

@Entity(name="SAMPLE")
@IdClass(SamplePk.class)
@Table(name="TABLE_SAMPLE")
public class Sample{
protected Integer id_sample;
protected Integer test;
public Sample() {}

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id_sample")
public Integer getId_sample() {
return id_sample;
}
public void setId_gem_import(Integer id_sample) {
this.id_sample= id_sample;
}

//remaining setter getter in place
}
SamplePK Class

public class SamplePK implements Serializable{
private static final long serialVersionUID = 3688605897932153056L;
protected Integer id_sample;
protected Integer test;

public SamplePK() {
}
public SamplePK(Integer id_sample) {
super();
this.id_sample= id_sample;
this.test= test;

}
//setter getter in place
//equals() , hashcode() and other constructor in place
}
persistence logic 

UserTransaction transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
transaction.begin();

//util class provides EntityManager
ConnectionUtil conn = new ConnectionUtil();
EntityManager entityManager = conn.getEntityManager();

//objList is List object holding List of obj[]
//obj[] contains data for a row to be insert in SAMPLE Table : id_sample at 0, test at 1
ListIterator itr = objList.listIterator();
int index = 0;
while(itr.hasNext()) {
index++;
Object[] obj = (Object[])itr.next();

Sample objSample = new Sample();
objSample.setTest(obj[1]);

entityManager.persist(objSample );
if(index%batch_size==0) { //batch_size is initialized to 50
entityManager.flush();
entityManager.clear();
}
}
transaction.commit();

最佳答案

也尝试注释复合键的其他字段。像这样的事情:

protected Integer id_sample;
protected Integer test;

@Id
@Column(name="id_sample")
public Integer getId_sample() {
return id_sample;
}
public void setId_gem_import(Integer id_sample) {
this.id_sample= id_sample;
}

@Id
@Column(name="test")
public Integer getTest() {
return test;
}
public void setTest(Integer test) {
this.test= test;
}

关于java - 使用entityManager将多条记录插入到包含@GenerateValue的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55632913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com