创建新实体加关联不起作用 [英] Creating new entity plus association not working
问题描述
我有两个实体 AppUser
和 UserGroup
.他们有一个 @ManyToMany
关系.
I am having two entities AppUser
and UserGroup
. They have a @ManyToMany
relationship.
我目前正在尝试为现有用户创建和关联一个新组,如下所示:
I am currently trying to create and associate a new group for an existing user like this:
POST http://localhost:8080/groups
{
"name": "Group 1",
"users": ["http://localhost:8080/users/1"]
}
问题是只创建了组 - 但与列出的用户没有关联 - 服务器仍然响应 201 Created
?!
The problem is that only the group gets created - but no association with the listed users - and still the server responds with 201 Created
?!
这是两个存储库:
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface AppUserRepository extends JpaRepository<AppUser, Long> {
AppUser findByUsername(@Param("username") String username);
}
@RepositoryRestResource(collectionResourceRel = "groups", path = "groups")
public interface UserGroupRepository extends JpaRepository<UserGroup, Long> {
List<UserGroup> findByName(@Param("name") String name);
}
下面你可以看到关系是如何定义的:
Below you can see how the relation is defined:
AppUser.java
AppUser.java
@Column(name="user_group_id")
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "app_user__user_group",
joinColumns = {
@JoinColumn(name = "app_user_id", nullable = false, updatable = false) },
inverseJoinColumns = {
@JoinColumn(name = "user_group_id", nullable = false, updatable = false)})
private Set<UserGroup> groups;
用户组.java
@Column(name = "app_user_id")
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "groups")
private Set<AppUser> users;
<小时>
注意:
如果我只传递一个字符串,而不是 users
的列表:
If I pass just a string, not a list for users
:
POST http://localhost:8080/groups
{
"name": "Group 1",
"users": "http://localhost:8080/users/1"
}
我得到的是:
{
"cause": {
"cause": null,
"message": "Cannot deserialize instance of java.util.Set out of VALUE_STRING token at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 7, column: 12] (through reference chain: mahlzeit.api.hibernate.model.UserGroup["users"])"
},
"message": "JSON parse error: Cannot deserialize instance of java.util.Set out of VALUE_STRING token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.Set out of VALUE_STRING token at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 7, column: 12] (through reference chain: mahlzeit.api.hibernate.model.UserGroup["users"])"
}
推荐答案
try
@Column(name = "app_user_id")
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "groups",cascade = CascadeType.ALL)
private Set<AppUser> users;
最终通过用户列表
{
"name": "Group 1",
"users": ["http://localhost:8080/users/1"]
}
for Cannot deserialize instance of java.util.Set 错误它需要一个用户列表,而不是单个用户的实例
for Cannot deserialize instance of java.util.Set error it expect a list of users not instans of single user
这篇关于创建新实体加关联不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!