Creating new entity plus association not working

99封情书 提交于 2019-12-18 09:24:11

问题


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

The problem is that only the group gets created - but no association with the listed users - and still the server responds with 201 Created?!

These are the two repositories:

@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

@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;

Note:

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

what I get is:

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

来源:https://stackoverflow.com/questions/47376620/creating-new-entity-plus-association-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!