我有两个实体 AppUser
和 UserGroup
,它们之间有一个 @ManyToMany
的关系。
我目前正在尝试像这样为现有用户创建并关联一个新组:
POST http://localhost:8080/groups
{
"name": "Group 1",
"users": ["http://localhost:8080/users/1"]
}
问题在于只创建了群组,但没有与列出的用户建立联系,而且服务器仍然响应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);
}
以下是关系的定义:
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;
UserGroup.java
@Column(name = "app_user_id")
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "groups")
private Set<AppUser> users;
注意:
如果我只传递一个字符串而不是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"])"
}
@ManyToMany
关联上不应该有@Column
注解。因此,首先要将其移除。 - Alan HayJpaRepository
的原因..如果你找到了一个好的解决方案,请考虑在这里回答。^^ - Stefan Falk