【发布时间】:2018-03-26 22:54:06
【问题描述】:
我已经尝试过使用休眠、JPA 和 JSON 进行 spring rest。 我必须像下面这样的实体:
大学.java
@Entity()
@Table(name = "university")
public class University extends BaseEntity {
private String uniName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "university_id", foreignKey = @ForeignKey(name = "university_id"))
private Collection<Student> students;
//setters and getters
}
学生.java
@Entity
@Table(name = "student")
public class Student extends BaseEntity {
private String stuName;
@ManyToOne(fetch = FetchType.EAGER)
@JsonIgnoreProperties("students")
private University university;
//setters and getters
}
我的数据库中有这个虚拟值。
[
{
"id": 1,
"uniName": "uni1",
"students": [
{
"id": 1,
"stutName": "st1",
"university": {
"id": 1,
"uniName": "uni1"
}
},
{
"id": 2,
"stutName": "st2",
"university": {
"id": 1,
"uniName": "uni1"
}
}
]
}
]
第一次尝试:当我尝试用学生更新大学时,没有成功 这是我的休眠日志
Hibernate:
select
university0_.id as id1_5_1_,
university0_.uniName as uniName2_5_1_,
students1_.university_id as universi3_4_3_,
students1_.id as id1_4_3_,
students1_.id as id1_4_0_,
students1_.stuName as stuName2_4_0_,
students1_.university_id as universi3_4_0_
from
university university0_
left outer join
student students1_
on university0_.id=students1_.university_id
where
university0_.id=?
Hibernate:
update
student
set
stuName=?,
university_id=?
where
id=?
Hibernate:
update
university
set
uniName=?
where
id=?
Hibernate:
update
student
set
stuName=?,
university_id=?
where
id=?
第二次尝试:但是当我第二次发布相同的数据时它是成功的并且休眠日志是
Hibernate:
select
university0_.id as id1_5_1_,
university0_.uniName as uniName2_5_1_,
students1_.university_id as universi3_4_3_,
students1_.id as id1_4_3_,
students1_.id as id1_4_0_,
students1_.stuName as stuName2_4_0_,
students1_.university_id as universi3_4_0_
from
university university0_
left outer join
student students1_
on university0_.id=students1_.university_id
where
university0_.id=?
Hibernate:
select
student0_.id as id1_4_0_,
student0_.stuName as stuName2_4_0_,
student0_.university_id as universi3_4_0_
from
student student0_
where
student0_.id=?
Hibernate:
select
student0_.id as id1_4_0_,
student0_.stuName as stuName2_4_0_,
student0_.university_id as universi3_4_0_
from
student student0_
where
student0_.id=?
Hibernate:
update
student
set
university_id=?
where
id=?
Hibernate:
update
student
set
university_id=?
where
id=?
和第一个不一样!!
我在休眠注释中做错了什么,或者如果我的 JSON 注释中缺少某些内容,为什么第二个尝试工作。
更新:这是我的编辑服务。
@Override
@Transactional/*(propagation = Propagation.NESTED)*/
public T edit(T entity) throws Exception {
return entityManager.merge(entity);
}
感谢任何帮助和建议。
【问题讨论】:
-
发布持久化数据的代码。
-
@Abdullah Khan 我更新了我的问题
-
您的映射错误。阅读 Hibernate 手册,了解如何正确映射双向 OneToMany 关联。
-
我在 hibernate 手册中有 JSON 序列化问题,我找不到解决方案来给我关于 JSON 序列化的正确解决方案,我已经问过这个stackoverflow.com/questions/46684015/…
-
JSON 序列化与 Hibernate 持久性完全无关。
标签: java spring hibernate spring-mvc jpa