使用entityManager将多个记录插入包含@GeneratedValue的表中

问题描述 投票:0回答:1

我是hibernate的新手,我遇到了将数据插入具有自动生成ID列的SAMPLE表的任务。

我正在使用EntityManager对象将对象持久化到db,但是收到错误:

类中的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();
java hibernate persist hibernate-entitymanager
1个回答
1
投票

尝试也可以注释复合键的其他字段。像这样的东西:

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.