-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 
Author Message
 Post subject: Hibernate many-to-many annotation does not insert child
PostPosted: Thu Mar 16, 2017 3:57 pm 
Newbie

Joined: Thu Mar 16, 2017 10:42 am
Posts: 7
Hello,

I have a many-to-many hibernate annotations project.

There are 3 tables - Course (courseid, coursename), Student (studentid, studentname) and student_course (studentid, courseid).

There are 2 entities - Course and Student. Student entity is the owner.

I have coded the 2 entities as follows:

Code:
package com.statestreet.pojo;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;

@Entity
@Table(name = "STUDENT")
public class Student implements java.io.Serializable
{
   /**
    *
    */
   private static final long serialVersionUID = 1L;
   private int studentId;
   private String studentName;
   private Set<Course> courses;
   
   public Student() {
       
   }
    
   public Student(int id, String name) {
     studentId = id;
     studentName = name;
   }
   
   public Course addCourse(Course inCourse) {
      this.getCourses().add(inCourse);
      inCourse.addStudent(this);
      return inCourse;
   }
   
   public Course removeCourse(Course inCourse) {
      getCourses().remove(inCourse);
      inCourse.removeStudent(this);
      return inCourse;
   }

   @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
     @JoinTable(name="student_course", joinColumns= {
                   @JoinColumn(name="STUDENTID", nullable = false, updatable = false) },                      
          inverseJoinColumns= {@JoinColumn(name="COURSEID",
                       nullable = false, updatable = false) })
   public Set<Course> getCourses(){
      return this.courses;
   }
   
   public void setCourses(Set<Course> courses) {
      courses = courses;
      for (Course c : courses) {
         c.addStudent(this);
      }
   }
    
   
   @Id
   @Column(name="STUDENT_ID", nullable=false)
   public int getStudentId() {
        return studentId;
   }
 
   public void setStudentId(int id) {
     this.studentId = id;
   }
 
   @Column(name="STUDENT_NAME", nullable=false)
   public String getStudentName() {
     return this.studentName;
   }
 
   public void setStudentName(String name) {
     this.studentName = name;
   }
}


Code:
package com.statestreet.pojo;

import java.util.HashSet;
import java.util.Set;
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;

@Entity
@Table(name="COURSE")
public class Course implements Serializable
{
   /**
    *
    */
   private static final long serialVersionUID = 1L;
   private int courseId;
   private String courseName;
    private Set<Student> students;
      
   
   public Course() {
      
   }
   
   public Course(int courseId, String courseName)
   {
      this.courseId = courseId;
      this.courseName = courseName;
      students = new HashSet<Student>();
   }
   
    @Id
    @Column(name="COURSE_ID", nullable=false)
    public int getCourseId()
    {
       return courseId;
    }
   
    public void setCourseId(int courseId)
    {
       this.courseId = courseId;
    }
   
    @Column(name="COURSE_NAME", nullable=false)
    public String getCourseName()
    {
       return courseName;
    }
   
    public void setCourseName(String courseName)
    {
       this.courseName = courseName;
    }
   
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "courses")
     public Set<Student> getStudents()
      {
         return students;
      }
      
      public void setStudents(Set<Student> students)
      {
         this.students = students;
      }
      
      public void addStudent(Student s1) {
         
         this.getStudents().add(s1);
      
      }
      
      public void removeStudent(Student s1) {
         this.getStudents().remove(s1);
      }
}


At the DAO layer, I am adding a new student like so:

Code:
public Student addStudent(Student std)
   {
      Student student = null;
      try
      {
         Transaction transaction = session.beginTransaction();
         session.save(std);
            transaction.commit();
            sessionFactory.close();
         } catch (Exception e) {
         e.printStackTrace();
      }
      return student;
   }


From the client, I call the DAO and pass the new student like this:

Code:
public static void main(String[] args) {
        Student student = new Student();
        student.setStudentId(102);
        student.setStudentName("Jayashree Ravi");
        Set<Course> stdcourses = new HashSet<Course>();
        Course course1 = new Course(1, "CORE JAVA");
        Course course2 = new Course(2, "J2EE-Hibernate");
        stdcourses.add(course1);
        stdcourses.add(course2);
        student.setCourses(stdcourses);
         StudentDao stdDao = new StudentDao();
         stdDao.addStudent(student);
   }


Now, my problem is that while data is getting inserted into the student table, although I have defined the mapping as stated above in both Student and Course entities, as well as defined foreign key constraints in the database level, when I save the student entity, only the student table in the database shows the new row. The student_course table and Course table do not get populated at all. I tried working around this for a long time but no success. What could I be doing wrong?


Top
 Profile  
 
 Post subject: Re: My hibernate many-to-many annotation project does not insert
PostPosted: Thu Mar 16, 2017 4:46 pm 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
You need to cascade the save entity state transition. Check out this article for more info.


Top
 Profile  
 
 Post subject: Re: Hibernate many-to-many annotation does not insert child
PostPosted: Fri Mar 17, 2017 8:14 am 
Newbie

Joined: Thu Mar 16, 2017 10:42 am
Posts: 7
Hi Vlad, thank you so much, I am presently trying it out.... have not had success so far....


Top
 Profile  
 
 Post subject: Re: Hibernate many-to-many annotation does not insert child
PostPosted: Fri Mar 17, 2017 10:27 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
You added this?

Code:
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "courses", cascade = CascadeType.PERSIST)
public Set<Student> getStudents()
{
         return students;
}


Top
 Profile  
 
 Post subject: Re: Hibernate many-to-many annotation does not insert child
PostPosted: Fri Mar 17, 2017 12:12 pm 
Newbie

Joined: Thu Mar 16, 2017 10:42 am
Posts: 7
Yes, I'm still getting this following exception. Tried both CascadeType.ALL and CascadeType.PERSIST.

Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: net.viralpatel.hibernate.Meeting
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:165)
at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:899)
at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1308)
at org.hibernate.persister.collection.OneToManyPersister.recreate(OneToManyPersister.java:184)
at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:67)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at net.viralpatel.hibernate.Main.main(Main.java:39)


Top
 Profile  
 
 Post subject: Re: Hibernate many-to-many annotation does not insert child
PostPosted: Fri Mar 17, 2017 12:13 pm 
Newbie

Joined: Thu Mar 16, 2017 10:42 am
Posts: 7
Yes, I'm still getting this following exception. Tried both CascadeType.ALL and CascadeType.PERSIST.

Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing:


Top
 Profile  
 
 Post subject: Re: Hibernate many-to-many annotation does not insert child
PostPosted: Fri Mar 17, 2017 1:24 pm 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
The Meeting entity does not show in your mapping. However, you know what to do now. Check out our [User Guide for more details](http://docs.jboss.org/hibernate/orm/5.2 ... Guide.html).


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.