简体   繁体   English

hibernate - 保存实体,其中包含一个实体(已存在于db中)

[英]hibernate - saving entity with an entity in it (that already exists in the db)

for simplicity, here is my simplified model: 为简单起见,这是我的简化模型:

I got 2 entities: 我有2个实体:

@entity
public class Student {
int id;
School school
...
}

and the school is an entity as well 学校也是一个实体

@entity
public class School {
int id;
...
}

im trying to pull a lot of data from a text file. 我试图从文本文件中提取大量数据。 some students have the same school instance, i wouldn't like multiple schools in my database with the same name, so my goal is to save each student in the student db , while making sure that 2 different students with the same school , wont create 2 entries in my school db. 有些学生有相同的学校实例,我不喜欢我的数据库中有多个同名的学校,所以我的目标是将每个学生保存在学生数据库中,同时确保2个不同的学生拥有相同的学校,不会创建我学校数据库中的2个条目。

problem is when i try to persist the students, it gives me an error: "detached entity passed to persist" , how do i tell hibernate, that the school in the student class is already exists in the database , and that it should use it instead? 问题是,当我试图坚持学生时,它给了我一个错误:“分离的实体传递给持久”,我怎么告诉hibernate,学生类中的学校已经存在于数据库中,并且它应该使用它代替?

thanks 谢谢

Map it with @ManyToOne(cascade=ALL) . 使用@ManyToOne(cascade=ALL)映射它。

"the same name" would not suffice though, you should have the same ID. 但是“同名”是不够的,你应该拥有相同的ID。 For that to work, you'd need to make sure your School object is taken from the DB before setting it to the Student 对于工作,你需要确保你的School对象从DB采取将其设置为学生前

There is a method on the session called merge(). 会话中有一个名为merge()的方法。 Use that instead of saveOrUpdate(); 使用它而不是saveOrUpdate();

Assuming associations are already set: 假设已经设置了关联:

Make sure you are working with the persisted Student entity. 确保您正在使用持久化的Student实体。 Do a search for the student entity, and set the school -> student to the student entity returned from the search. 搜索学生实体,并将学校 - >学生设置为从搜索返回的学生实体。

entity.find ( Student.class, student_id) entity.find(Student.class,student_id)

Otherwise, make sure the associations are annotated before doing the above. 否则,请确保在执行上述操作之前注释关联。

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

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