英文:
JPA Repository Join - Continuous Loop of data when retrieving data from DB
问题
我有两个仓库 - 用户(User)和地址(Address)。
用户与地址之间存在一对一的关系,它们通过ID进行关联。请参见下面的代码片段。当我使用JPA仓库提取数据时,我基本上会得到一个数据的不断循环。
例如:
<Data>
<User>
<id>1</id>
<name>Mary</name>
<dob>21/01/1990</dob>
<Address>
<id>1</id>
<address>123 Main Street</address>
<User>
<id>1</id>
<name>Mary</name>
<dob>21/01/1990</dob>
<Address>
<id>1</id>
<address>123 Main Street</address>
<User>
....
等等,像这样不断循环,导致我的查询运行时间很长。有没有办法阻止用户对象在地址对象内部被返回?非常感谢您的帮助。
@Entity
@Data
@Table(name = "ADDRESS")
public class Address {
@Id
@Column()
private String id;
@Column()
private String address;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private User user;
}
@Entity
@Data
@Table(name = "User")
public class User {
@Id
@Column()
private String id;
@Column()
private String name;
@Column()
private String dob;
@OneToOne()
@JoinColumn(name = "id")
private Address address;
}
英文:
I have two repositories - User and Address.
User has a one to one relationship with Address and they are linked by ID. See below code snippets. When I pull data using a JPA repository, I get basically a constant loop of data.
EG:
<Data>
<User>
<id>1</id>
<name>Mary</name>
<dob>21/01/1990</dob>
<Address>
<id>1<id>
<address>123 Main Street</address>
<User>
<id>1</id>
<name>Mary</name>
<dob>21/01/1990</dob>
<Address>
<id>1<id>
<address>123 Main Street</address>
<User>
....
and so on like this causing my query to take a large amount of time to run. Is there anyway to stop the User object from being returned within the Address object? Any help would be greatly appreciated.
@Entity
@Data
@Table(name = "ADDRESS")
public class Address{
@Id
@Column()
private String id;
@Column()
private String address;
@OneToOne (fetch = FetchType.LAZY)
@JoinColumn(name = "id")
private User user;
}
@Entity
@Data
@Table(name = "User")
public class User{
@Id
@Column()
private String id;
@Column()
private String name;
@Column()
private String dob;
@OneToOne ()
@JoinColumn(name = "id")
private Address address;
}
答案1
得分: 0
这是正常行为。序列化器调用 getter 方法来序列化数据,这些数据会被 Hibernate 代理
截取,即使它们是延迟加载的也会加载数据。为了防止这种情况,您需要在 User
类的 address
字段上添加 @JsonBackReference
,并在 Address
类的 user
字段上添加 @JsonManagedReference
。
英文:
This is normal behaviour. Serializers call getters to serialize data which are intercepted by the Hibernate Proxy
loading the data even if they are lazy. To prevent this, You have to add @JsonBackReference
to the address
field in your User
class, and @JsonManagedReference
to the user
field in your Address
class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论