[英]Hibernate Many-To-Many Relationship with Composite Key Circular JSON
我在使用 JPA/Hibernate 的 Spring 引導中具有與一些額外屬性和復合鍵的多對多實體關系,但是實體/實體的 JSON 序列化導致循環 Z0ECD11C1D7A287401DZDA2 拋出異常。
基本表結構如下(cols = entity/table, rows = attributes):
用戶 | 用戶角色 | 角色 |
---|---|---|
ID | 用戶身份 | ID |
f_name | 角色 ID | 姓名 |
l_name | 分配_at | 別名 |
在 Spring Boot 中,這表示為以下關系:
@Embeddable
class UserRoleKey implements Serializable {
@Column(name = "user_id")
private long userId;
@Column(name = "role_id")
private long roleId;
public UserRoleKey() {}
// hash, equals omitted for brevity
// getter/setter for userId, roleId omitted for brevity
}
@Entity
@Table(name = "user_role")
class UserRole {
@EmbeddedId
private UserRoleKey id;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("userId")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("roleId")
private Role role;
@Temporal
@Column(name = "assigned_at")
private Date assignedAt;
public UserRole() {}
// hash, equals omitted for brevity
// getter/setter for user, role, assignedAt omitted for brevity
}
其中兩個單獨的實體表示為:
@Entity
@Table(name = "user")
class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String fName;
private String lName;
@OneToMany(mappedBy = "user")
private Set<UserRole> userRoles = new HashSet<>();
// hash, equals omitted for brevity
// getter/setter for fName, lName, userRoles omitted for brevity
}
@Entity
@Table(name = "role")
class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String alias;
@OneToMany(mappedBy = "role")
private Set<UserRole> roleUsers = new HashSet<>();
// hash, equals omitted for brevity
// getter/setter for name, alias, roleUsers omitted for brevity
}
每當通過存儲庫的findAll
方法通過 API 獲取User
的列表時,返回的User
JSON 會無限期地在User
上遞歸,從而導致異常。 User
實體的結果 JSON 如下所示:
User:
{
"id": 0,
"fName": "John",
"lName": "Doe",
"userRoles" = [
{
"user": {
// Infinite recursion!
"id": 0,
"fName": "John",
"lName": "Doe",
"userRoles" = [
....
]
},
"role": {
"id": 0,
"name": "Administrator",
"alias": "admin"
},
"assignedAt": "dummy_timestamp"
}, ...
]
}
如果關系用於相反方向,即通過Role
,則會出現同樣的問題。
我在這里缺少什么嗎? 我在 Hibernate/JPA/Spring 上瀏覽了大量不同的資源,但我似乎無法發現這里有什么問題。
您可以在一個關系上使用 @JsonIgnore 來打破循環。
如果你想獲得用戶 object 沒有附加用戶角色的用戶角色,你可以通過從角色 class 中刪除@OneToMany(mappedBy = "role")
來使這種關系單向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.