hibernate多对多中间表不保存数据问题

小北+小杨 发布于 2012/07/02 11:22
阅读 1K+
收藏 0
student类
@Entity
@Table(name="t_student")
public class Student {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
   
    @ManyToMany(
            cascade = {CascadeType.ALL},
            mappedBy = "student",
            targetEntity = com.hibernate.manytomany.Course.class
        )

    private Set<Course> course = new HashSet<Course>();

}

cource类

@Entity
@Table(name="t_course")
public class Course {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
   
    @ManyToMany(
        targetEntity=com.hibernate.manytomany.Student.class,
        cascade={CascadeType.ALL}
    )
    @JoinTable(
        name="student_course",
        joinColumns=@JoinColumn(name="course_id"),
        inverseJoinColumns=@JoinColumn(name="student_id")
    )
    private Set<Student> student = new HashSet<Student>();

}

测试类

public class Test {
    @org.junit.Test
    public void testSave(){
        Session session = null;
        Configuration cfg = new AnnotationConfiguration().configure();
        SessionFactory sf = cfg.buildSessionFactory();
        session = sf.getCurrentSession();
        session.beginTransaction();
       
        Student s = new Student();
        Course c = new Course();
       
        Set<Course> courses = new HashSet<Course>();
       
        s.setName("张三");
        c.setName("语文");
        courses.add(c);
        s.setCourse(courses);
       
        session.save(s);
        session.getTransaction().commit();
    }
}

现在两张表有数据,中间表没数据,各位看看哪里配错了,谢谢

 

加载中
返回顶部
顶部