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

时间:2019-04-11 12:49:00

标签: java hibernate persist hibernate-entitymanager

我是新来的休眠者,我一直坚持将数据插入具有自动生成的ID列的SAMPLE表中的任务。

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

  

IllegalArgumentException类:SamplePk,属性的设置方法: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();

1 个答案:

答案 0 :(得分:0)

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

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;
}