为什么不能在 spring data jpa 中保存数据

Why can not persist data in spring data jpa

在数据库中保存数据时出现异常Cannot handle managed/back reference 'defaultReference': back reference type not compatible with managed type。我在保留数据时遇到异常。我认为问题出在 @JsonManagedReference@JsonBackReference 注释中,但找不到问题所在。

下面是代码:

实体

@Entity
@Table(name = "user_master")
public class Users {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer user_id;

    private String name;

    @JsonManagedReference
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "users_roles", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
            @JoinColumn(name = "role_id") })
    private List<Roles> roles;

    // constructor and getter/setter
}

@Entity
@Table(name = "role_master")
public class Roles {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer role_id;

    private String name;

    @JsonBackReference
    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "roles")
    private List<Users> users;

    // constructor and getter/setter
}

服务

@Override
    public List<Users> addUserRole(List<Users> users) {
        for(Users user: users)
        {
            for(Roles role: user.getRoles())
            {
                role.getUsers().add(user);
            }
        }
        return userRepo.saveAll(users);
    }

控制器

@RequestMapping(value = "/adduserrole", method = RequestMethod.POST)
    public ResponseEntity<List<Users>> addUserRole(@RequestBody List<Users> users)
    {
        pojoService.addUserRole(users);
        return ResponseEntity.ok(users);
    }

邮递员

[
  {
    "name": "Jack",
    "roles": [
    {
        "name": "Engineer"
    },
    {
        "name": "Doctor"
    },
    {
        "name": "Charter Accountant"
    }
    ]
  }
]

异常

"message": "Cannot invoke \"java.util.List.add(Object)\" because the return value of \"com.rest.RestApiPojo.Entity.Roles.getUsers()\" is null",

@JsonManagedReference@JsonBackReference 应该用在一侧 OneToMany 和另一侧 ManyToOne 的双向关系中,或者当双方都是类型 OneToOne.

如果你仔细观察 JsonBackReference Doc 你就会明白这一点

Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration. Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.

在你的例子中你有双向 ManyToMany 这意味着在双方都有一个集合的引用。所以在你有 @JsonBackReference.

的那一边没有一个兼容的 属性

你的问题有 2 个解决方案 ManyToMany 关系

  1. 删除 @JsonManagedReference@JsonBackReference。选择要序列化和反序列化集合的一侧。转到您不希望其他集合被序列化和反序列化的另一侧,并使用注释 @JsonIgnore.
  2. 使用没有循环依赖的自定义 Dto,并让您的控制器使用这些 Dto 而不是普通实体。

你还有一个问题

你的控制器

@RequestMapping(value = "/adduserrole", method = RequestMethod.POST)
    public ResponseEntity<List<Users>> addUserRole(@RequestBody List<Users> users)
    {
        pojoService.addUserRole(users);
        return ResponseEntity.ok(users);
    }

需要用户列表作为输入。不是单个用户。所以当你想发送单个用户时,你的 JSON 应该是

[
  {
    "name": "Jack",
    "roles": [
    {
        "name": "Engineer"
    },
    {
        "name": "Doctor"
    },
    {
        "name": "Charter Accountant"
    }
    ]
  }
]