gpt4 book ai didi

java - 传递给持久化的分离实体 : com. carpooling.entity.Role;嵌套异常是 org.hibernate

转载 作者:太空宇宙 更新时间:2023-11-04 11:14:04 24 4
gpt4 key购买 nike

我在我的项目中使用 Spring Boot 和 Spring Data:

@Entity
public class User {
vate Long id;
private String firstName;
private String familyName;
@ManyToMany( fetch = FetchType.LAZY, cascade = CascadeType.ALL )
@JoinTable( name = "user_role", joinColumns = {
@JoinColumn( name = "USER_ID", nullable = false, updatable = false ) }, inverseJoinColumns = {
@JoinColumn( name = "ROLE_ID", nullable = false, updatable = false ) } )
private List<Role> roles;
//getters and setters
}

角色类:

@Entity
public class Role {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Long id;
private String roleName;

@ManyToMany( fetch = FetchType.LAZY, mappedBy = "roles" )
private List<User> users;
//getters and setters
}

添加用户方法:

public User AddUser( User user ) {
// TODO Auto-generated method stub
List<Role> roles = user.getRoles();
user.setRoles( roles );
return userRepsitory.save( user );
}

当我尝试添加新用户时,出现上面的错误,这是发送的 JSON 对象:

{"firstName":"fff","familyName":"ffff","roles":[{"id":1}, {"id":2}] }

最佳答案

由于您要级联非托管实体,因此如果您的实体确实有 id(如您的情况),jpa 会认为它们是独立的实体,并且您需要将它们管理起来,您只需使用提供的 id 从数据库中获取角色即可。

public User AddUser( User user ) {
// TODO Auto-generated method stub
List<Role> roles = new ArrayList<Role>();
for(Role entry :user.getRoles())
roles.add(roleDao.findOne(entry.getId()));
user.setRoles( roles );
return userRepsitory.save( user );
}

关于java - 传递给持久化的分离实体 : com. carpooling.entity.Role;嵌套异常是 org.hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45676485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com