【发布时间】:2019-04-11 12:48:59
【问题描述】:
我是 hibernate 的新手,我被困在将数据插入到具有自动生成的 ID 列的 SAMPLE 表中的任务中。
我正在使用 EntityManager 对象将对象持久保存到数据库中,但是出现错误:
类中的IllegalArgumentException:SamplePk,属性的setter方法:id_sample
预期类型:java.lang.Integer,实际值: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();
【问题讨论】:
-
嗯,你注释了
@IdClass(SamplePk.class),然后是@Id public Integer getId_sample()...现在,是SamplePk还是Integer? -
@Usagi,id_sample 在 DB 中是 int 类型,因此是 Integer..
-
你能告诉我们数据库模式吗?像
CREATE TABLE声明? -
@UsagiMiyamoto 很抱歉,但我不能,我实际上是在使用示例代码来演示我遇到的问题..在实际代码中..表有一个复合主键(两列)其中之一是自动生成的..这两个列都是数据库中的 int 类型。所以当我设置不同表列的值时,我没有设置自动生成列的值。但是,在设置所有值后,在调用 EntityManager.persist() 时,我得到了这个 IllegalArgumentException。
标签: java hibernate persist hibernate-entitymanager