Search code examples
javaspringhibernateorm

Why is it not cascading? I am tring to insert data into two tables using cascading but values is inserted for only on owning table


I am tring to insert data into two tables but values is inserted for only on owning table... Following are my codes:

Question Entity Class:

@Entity
@Table(name="ques")
public class Question {
    @Id
    private int id;
    private String question;
    @OneToMany(mappedBy = "question", cascade = javax.persistence.CascadeType.ALL)
    private List<Answer> answers;

Answer Entity Class:

@Entity
@Table(name="ans")
public class Answer {
    @Id
    private int id;
    private String answer;
    @ManyToOne
    private Question question;

Main Class:

public class App {

    public static void main(String[] args) {
        
        SessionFactory factory = new Configuration().configure().buildSessionFactory();
        Session s = factory.openSession();
        Transaction tx = s.beginTransaction();
        
        
        Answer a1 = new Answer(5001, "answer 1...");
        Answer a2 = new Answer(5002, "answer 2...");
        Answer a3 = new Answer(5003, "answer 3...");
        
        List<Answer> list = new ArrayList<>();
        
        Question q1 = new Question();
        q1.setId(1);
        q1.setQuestion("question...?");     
        q1.setAnswers(list);
        
        a1.setQuestion(q1);
        a2.setQuestion(q1);
        a3.setQuestion(q1);
        
        s.save(q1);
        
        tx.commit();
        
        s.close();
        factory.close();
        
        System.out.println("Done");
    }

}

Output:

Hibernate: 
    insert 
    into
        ques
        (question, id) 
    values
        (?, ?)
Nov 26, 2023 12:40:27 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PoolState stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/myhiber]
Done

Question is inserted but answers are not inserted. What am I doing wrong here?


Solution

  • This is wrong:

    q1.setAnswers(list);
    

    because list is empty, you need to do something like this:

    List<Answer> list = new ArrayList<>(Arrays.asList(a1, a2, a3));