【发布时间】:2023-04-07 20:02:01
【问题描述】:
我有一个用例,一个用户可以拥有多个房子。这就是模型的样子 应用程序用户.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 模型的错误映射。