【问题标题】:What exactly happens when I use session.save instead of session.persist?当我使用 session.save 而不是 session.persist 时究竟会发生什么?
【发布时间】:2021-10-18 18:01:52
【问题描述】:

我知道这是一个非常常见的话题。我也阅读了很多与它相关的博客和帖子,但其中大多数只是告诉save() 返回一个标识符和persist() 的返回类型为 void 的区别。两者都属于包org.hibernate

我也看过以下帖子:

我有一个数据库如下。

对于那些不使用IntelliJ IDEA 的人,instructor_id 用作表course 中的外键,该表引用instructor(id),同样适用于另一个表。

我试图通过以下方式将课程保存给讲师:

session.beginTransaction();

// get the instructor from the database
int theId = 1;
Instructor tempInstructor =
    session.get(Instructor.class, theId);

// create some courses
Course tempCourse1 = new Course("Java");
Course tempCourse2 = new Course("Maven");
tempInstructor.add(tempCourse1, tempCourse2);

session.save(tempInstructor);

// Commit transaction
session.getTransaction().commit();

Instructor类中的相关条目:

@OneToMany(mappedBy = "instructor",
            cascade = {CascadeType.DETACH, CascadeType.PERSIST,
                    CascadeType.MERGE, CascadeType.REFRESH})
private List<Course> courses;

Instructor中的add方法-

public void add(Course... tempCourse) {

    if (courses == null) {
        courses = new ArrayList<>();
    }

    for (Course course : tempCourse) {
        courses.add(course);
        course.setInstructor(this);
    }


}

Course类中的相关条目:

@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.PERSIST,
            CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumn(name = "instructor_id")
private Instructor instructor; // Associated Entity

当我尝试使用session.save(tempInstructor); 保存讲师时,当我使用session.save() 时,没有课程与讲师一起保存,但是当我使用session.persist() 时,两个课程也都保存了。我知道save() 会立即返回一个标识符和INSERTS 对象,那它为什么不保存课程呢?

我也在某处读过

save() 在 具有扩展会话/持久性的长期对话 上下文。

当我调用 save 时会发生什么?为什么没有保存对象?

【问题讨论】:

  • 尝试在save之后立即调用Session.flush
  • 试过了,不行。

标签: java hibernate session


【解决方案1】:

在您的示例中,tempCourse1tempCourse2 处于分离状态,因此要建立关系,您需要将它们持久化。

savepersist 做同样的事情,但 save 是 Hibernate 的 API,persist 是 JPA 规范的一部分。

在您的实体上,您有 CascadeType.PERSIST,它仅与 persist 方法相关。要使save 的行为相同,您应该将org.hibernate.annotations.CascadeType#SAVE_UPDATE 添加到您的ManyToOne 注释中。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2023-03-29
    • 2012-06-06
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多