javahibernatepersisthibernate-entitymanager

Inserting multiple records into a table containing @GeneratedValue using entityManager


I am new to hibernate and I am stuck with a task of inserting data into SAMPLE table that has an auto generated ID column.

I am using EntityManager object to persist the object into db however, getting error:

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

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

Please find my code below

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();

Solution

  • Try annotating the other field(s) of the composite key, too. Something like this:

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