19

I have a Student entity. My idea is to collect multiple student objects in an ArrayList and save all objects from that list to the database. When do you use @ElementCollection annotation? Does it apply to situations like this?

Student:

package basic;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    public Student() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }

    public Student(String name) {
        this.name = name;
    }

}

Runner:

package basic;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Runner {

    public static void main(String[] args) {

        SessionFactory sessionFactory = new Configuration().configure("/basic/hibernate.cfg.xml").buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        List<Student> students = new ArrayList<>();

        students.add(new Student("Michael"));
        students.add(new Student("Dave"));
        students.add(new Student("Tom"));
        students.add(new Student("Dinesh"));
        students.add(new Student("Lakshman"));
        students.add(new Student("Cruise"));

        session.save(students);

        session.getTransaction().commit();
        session.close();
    }

}

Error

Exception in thread "main" org.hibernate.MappingException: Unknown entity: java.util.ArrayList
    at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
    at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1596)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:668)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:660)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:655)
    at basic.Runner.main(Runner.java:27)

3 Answers 3

24

You have to do something like this:

for(Student student : students) {
    session.save(student);
}

If you want to save entity you should map it. ArrayList<> is not mapped entity. Student has mapping so you should save it separately.

Sign up to request clarification or add additional context in comments.

1 Comment

obviously this is how you do it, the problem is O(n) queries which you made zero attempt to solve
4

@ElementCollection you should use to define relation between object - here you have nice explenation https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection

To save list of object, you need to iterate by objects, something like this -> How to insert multiple rows into database using hibernate?

Comments

1

I would further recommend to use another Hibernate command to avoid an Out Of Memory error...

SessionFactory sessionFactory = config.buildSessionFactory();
    Session session = sessionFactory.openSession();
     
    Transaction transaction = session.beginTransaction();
     
    for (int i = 0 ; i < students.size(); i++) {
         session.save(students.get(i));
         
        if (i % 100 == 0) {//a batch size for safety
            session.flush();
            session.clear();
        }
    }
     
    transaction.commit();
    session.close();
    sessionFactory.close();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.