Hibernate:一对多映射导致循环对象
Posted
技术标签:
【中文标题】Hibernate:一对多映射导致循环对象【英文标题】:Hibernate: One to many mapping is leading to circular objects 【发布时间】:2021-03-13 01:02:52 【问题描述】:我有一个用例,一个用户可以拥有多个房子。这就是模型的样子 应用程序用户.java
@Getter
@Setter
@Entity
public class ApplicationUser
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
@Column(nullable = false)
private String emailId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "applicationUser", cascade = CascadeType.REMOVE)
private List<House> houses;
House.Java
@Getter
@Setter
@Entity
public class House
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
@ManyToOne()
@JoinColumn(name = "application_user")
private ApplicationUser applicationUser;
@Column(name = "House_Name")
private String houseName;
HouseRepository
public interface HouseRepository extends JpaRepository<House, Long>
public House findByHouseName(String houseName);
public List<House> findAllByApplicationUser_Username(String userName);
每当我尝试检索任何房子时,房子对象都包含用户对象,而用户对象又包含房子对象。这会无限进行。
"id": 3,
"applicationUser":
"id": 2,
"username": "test",
"emailId": "testmail",
"houses": [
"id": 3,
"applicationUser":
"id": 2,
"username": "test",
"emailId": "testmail",
"houses": [
"id": 3,
"applicationUser":
"id": 2,
"username": "test",
"emailId": "testmail",
"houses": [
我该如何阻止这种情况发生?
【问题讨论】:
@JsonIdentityInfo
。这与 Hibernate 无关,与 JSON 序列化 (Jackson) 无关。
休眠正常工作;但是,这更像是数据库模型到数据库后备存储之上的 OO 模型的错误映射。
看看类似的问题:Jackson serialize problem in @ManyToMany relationship, serialization issue. Only first object of the same entity serializes well, Jackson/Hibernate meta get methods and serialization
【参考方案1】:
由于您的House
有一个ApplicationUser
并且您的ApplicationUser
有一个House
s 的列表,因此您已将这些类定义为循环的。
您的面向对象模型可能与数据库模型 100% 相同。这可能是个坏主意;就像在家庭应用程序的模型中一样,您通常不会将应用程序保存在嵌入应用程序的用户中。
阅读What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?了解更多详情。
【讨论】:
以上是关于Hibernate:一对多映射导致循环对象的主要内容,如果未能解决你的问题,请参考以下文章