spring - 引起:org.hibernate.PersistentObjectException:分离的实体在创建新actor时传递给持久化
问题描述
有以下两个具有多对多映射的实体,我想将带有角色的 Actor 保存到现有角色的数据库中。
@Entity
@Data
@Table(name = "actor")
@NoArgsConstructor
public class Actor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long actorId;
@Column(unique = true)
@NotNull
private String username;
@NotNull
private String password;
@Column(unique = true)
@NotNull
private String email;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "actor_role", joinColumns = @JoinColumn(name = "actorId"), inverseJoinColumns = @JoinColumn(name = "roleId"))
private Collection<Role> roles;
}
@Entity
@Table(name = "role")
@Data
@NoArgsConstructor
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long roleId;
@Column(unique = true)
@NotNull
private String roleName;
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany(mappedBy = "roles")
private Collection<Actor> actors;
public Role(String roleName) {
super();
this.roleName = roleName;
}
}
当我尝试使用 JPA ActorRepository 创建新演员时
final Actor actor = new Actor();
actor.setUsername(user.getUsername());
actor.setPassword("");
actor.setEmail(user.getUsername());
List<Role> newRoles = new ArrayList<>();
for (GrantedAuthority authority : authentication.getAuthorities()) {
Role role = roleRepo.findByRoleName(authority.getAuthority());
newRoles.add(role);
}
actor.setRoles(newRoles);
Actor savedActor = actorRepo.save(actor);
我得到以下错误
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: org.db.model.Role
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)
你能帮我解决这个问题吗,我是JPA的新手。
提前致谢
解决方案
推荐阅读
- xslt - BizTalk 映射:从 soapenv:Header 获取值
- javascript - 如何使用 TestCafe 访问应用程序操作?
- python - Python多条重复记录
- bash - EC2 用户数据未启动我的应用程序
- apache-kafka - 如何查看从某个 IP 地址连接的 kafka 客户端应用程序?
- swift - 将 CGImage 转换为 MTLTexture 而不进行预乘
- javascript - 我可以在悬停时使用 highcharts 列堆叠而不突出整个系列吗
- python - 如何通过使用python在csv文件中搜索字符串的第一个单词来打印整个字符串(在单元格中)
- java - 在复杂的 HashMap 中使用 StringJoiner
- python - OpenCV Videowriter 无法在 Ubuntu 16.04 上运行