我在https://examples.javacodegeeks.com/enterprise-java/jpa/one-to-many-unidirectional-mapping-in-jpa/
中解释了在用户与角色实体之间实现单向OneToManyUserDataImpl.java:
@Entity
public class UserDataImpl {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
.
.
.
@OneToMany(targetEntity = RoleDataImpl.class, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_role_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
//Constructors
//Getters and setters
//Hashcode and equals
//toString
}
RoleDataImpl.java:
@Entity
public class RoleDataImpl {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private byte permissionsInByte = 0;
//Constructors
//Getters and setters
//Hashcode and equals
//toString
}
我的UserRepository和RoleRepository都扩展了JpaRepository。我在保存之前创建了一个用户对象并将一个Role对象附加到它。
我在Spring Data JPA中保存用户时出现以下错误:
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.entity.impl.RoleDataImpl; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.entity.impl.RoleDataImpl
.
.
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.wehub.entity.impl.RoleDataImpl
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:765)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:758)
.
.
当我删除orphanRemoval和cascades时:
@OneToMany(targetEntity = RoleDataImpl.class)
@JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_role_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
我得到DataIntegrityException(第一个对象正常保存)。因为user_roles表中的role_id将对其具有唯一约束。但是我希望在删除用户时删除user_roles条目。请帮忙。
答案 0 :(得分:1)
异常消息告诉您错误:传递给persist的分离实体:com.entity.impl.RoleDataImpl 这意味着您的#include <Windows.h>
#include <GL\glew.h>
#include <GL\freeglut.h>
class Test
{
public:
Test() { }
void enable();
};
void Test::enable()
{
//glEnable(GL_DEPTH_TEST); // Doesn't compile? Error - Error C2146 syntax error: missing ';'
}
int main()
{
glEnable(GL_DEPTH_TEST);
}
实例拥有对{{User
的引用1}}反过来不由您的Role
管理。
它应该像这样工作:
EntityManager