创建新实体加关联无效

时间:2017-11-19 12:04:20

标签: spring spring-data-jpa spring-data-rest

我有两个实体AppUserUserGroup。他们有@ManyToMany的关系。

我目前正在尝试为现有用户创建 关联这样的新群组:< / p>

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"])"
}

1 个答案:

答案 0 :(得分:0)

尝试

@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"]
}

用于无法反序列化java.util.Set错误的实例 它期望用户列表而不是单用户实例