简体   繁体   English

Hibernate不保存值的集合

[英]Hibernate not saving collection of values

Okay, I've used Hibernate in several projects now but I did not learn its intricacies before using it. 好吧,我现在已经在几个项目中使用了Hibernate,但在使用之前我没有学习它的复杂性。 I started with looking at codes that used JPA Annotations and integrated with Spring and everything worked well. 我开始查看使用JPA Annotations并与Spring集成的代码,一切运行良好。 But now that I want to teach basic Hibernate to my students and I'm in the process of creating an example and using the documentation tutorial Chapter 1, I'm having a problem with saving a Set of collection values in one persistent class. 但是现在我想向我的学生讲授基本的Hibernate,并且我正在创建一个示例并使用文档教程第1章,我遇到了在一个持久化类中保存一组集合值的问题。

Here's the persistent class... 这是持久性阶级......

public class Student {
    private Long id;
    private String firstName;
    private String lastName;
    private Set<Course> courses = new HashSet<Course>();
    private Set<String> contactDetails = new HashSet<String>();

    //getters and setters
}

The mapping file... 映射文件......

<hibernate-mapping package="com.phoenixone.school.model">
    <class name="Student" table="student">
        <id name="id" column="studentId">
           <generator class="native" />
        </id>

        <property name="firstName" />
        <property name="lastName" />

        <set name="courses" table="student_course" lazy="false">
            <key column="studentId" />
           <many-to-many column="courseId" class="Course" />
        </set>

        <set name="contactDetails" table="contactDetails">
            <key column="studentId" />
            <element type="string" column="contactDetail" />
        </set>
    </class>
</hibernate-mapping>

The DAO (saving part) DAO(保存部分)

public class StudentDaoHibernate {
    public void save(Student student){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        session.save(student);
        session.getTransaction().commit();
    }
}

The testing part... 测试部分......

public class TestStudentDaoHibernate {
    public static void main(String[] args) {
        CourseDaoHibernate courseDao = new CourseDaoHibernate();

        Course c1 = new Course();
        c1.setCourseCode("CWD");
        c1.setCourseName("Web Dev");
        courseDao.save(c1);

        Set<Course> courses = new HashSet<Course>();
        courses.add(c1);

        Student student = new Student();
        student.setFirstName("Bob");
        student.setLastName("Santos");
        student.setCourses(courses);
        student.getContactDetails().add("123456789");                 

                StudentDaoHibernate dao = new StudentDaoHibernate();
        dao.save(student);
    }
}

When I execute these lines of code... 当我执行这些代码行时......

Session session = HibernateUtil.getSessionFactory().getCurrentSession()
session.beginTransaction();
Student student = (Student)session.createCriteria(Student.class)
             .add(Restrictions.eq("id", new Long(1))).uniqueResult();
System.out.println("First Name: " + student.getFirstName());
System.out.println("Last Name: " + student.getLastName());

System.out.println("Courses enrolled with...");
for(Course c:student.getCourses()){
    System.out.println(c.getCourseName());
}

System.out.println("Contact details...");
for(String s:student.getContactDetails()){
    System.out.println(s);
}

What I get is this... 我得到的是这个......

First Name: Bob 名字:鲍勃
Last Name: Santos 姓氏:桑托斯
Courses enrolled with... 注册的课程......
Web Dev Web Dev
Contact details... 联系方式...

Which leads me to the conclusion that the String "123456789" was not saved. 这导致我得出字符串“123456789”未保存的结论。 What do you think is the problem with my code? 您认为我的代码有什么问题? Thanks! 谢谢!

You need to add a cascade attribute to your set elements for courses and contactDetails. 您需要为课程和contactDetails的set元素添加级联属性。 This defines what operations performed on the parent entity will be applied to the child entity. 这定义了对父实体执行的操作将应用于子实体。 The default value is none which is why when you saved the Student none of the child elements in the sets where saved. 默认值为none,这就是为什么保存Student时保存的集合中没有子元素的原因。

Adding cascade="all,delete-orphan" will cover all operations but you can be more restrictive if you wish. 添加cascade =“all,delete-orphan”将涵盖所有操作,但如果您愿意,可以限制更多。 See here in the Hibernate 4.3 reference for more details. 这里的更多细节休眠4.3参考。

After session.save(student); session.save(student); try adding session.flush(); 尝试添加session.flush();

I'd recommend creating a Contract class and using that instead of a String. 我建议创建一个Contract类并使用它而不是String。 It's a better abstraction, and the evidence that Hibernate dealt with your Course class just fine suggests that it'll work well with Contract, too. 这是一个更好的抽象,并且Hibernate处理你的课程课程的证据很好,这表明它也能很好地与Contract合作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM