gpt4 book ai didi

java - hibernate : One to many mapping is leading to circular objects

转载 作者:行者123 更新时间:2023-12-05 06:56:44 24 4
gpt4 key购买 nike

我有一个用例,其中单个用户可以拥有多个房屋。这是模型的样子应用程序用户.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;
}

房子.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;

}

房屋资料库

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": [

如何阻止这种情况发生?

最佳答案

因为你的 House 有一个 ApplicationUser 而你的 ApplicationUser 有一个 House 的列表,你已经将类定义为循环的。

很可能您的面向对象模型与数据库模型 100% 相同。这可能是个坏主意;与在家庭应用程序模型中一样,您通常不会将应用程序保留在嵌入应用程序的用户中。

阅读What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?了解更多详情。

关于java - hibernate : One to many mapping is leading to circular objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65084895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com