实体映射: - 传递给持久化的分离实体

时间:2017-12-12 10:01:05

标签: java jpa mapping hibernate-mapping

我正在尝试保存对象但是我收到以下错误

org.hibernate.PersistentObjectException: detached entity passed to persist: com.tets.ditacedentity.entity.Department

使用CascadeType.MERGE实际上我得到了解决方案,但我想使用CascadeType.ALL来解决我想要使用CascadeType.ALL保存实体的问题。请任何人告诉我解决方案。提前谢谢。

用户实体类:----

@Entity
@Table(name = User.TABLE_NAME, indexes = { @Index(columnList = User.COLUMN_USER_ID, unique = true) })
public class User {
    public static final String TABLE_NAME = "User";
    public static final String COLUMN_USER_ID = "pk_user_id";
    public static final String COLUMN_USER_FNAME = "user_fname";
    public static final String COLUMN_USER_EMAIL = "user_email";

    public static final String DEPARTMENT_FOREIGN_KEY = "fk_department";

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = COLUMN_USER_ID)
    private int userId;

    @Column(name = COLUMN_USER_FNAME, columnDefinition = "VARCHAR(255)")
    private String userName;

    @Column(name = COLUMN_USER_EMAIL, columnDefinition = "VARCHAR(255)")
    private String userEmail;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = DEPARTMENT_FOREIGN_KEY, foreignKey = 
    @ForeignKey(name = DEPARTMENT_FOREIGN_KEY))
    private Department dept;

    //Getter Setter

}

部门实体类:-----

@Entity
@Table(name = Department.TABLE_NAME, indexes = { @Index(columnList = Department.COLUMN_DEPARTMENT_ID, unique = true)})
public class Department {
    public static final String TABLE_NAME = "Deepartment";
    public static final String COLUMN_DEPARTMENT_ID = "dept_id";
    public static final String COLUMN_DEPARTMENT_NAME = "user_fname";


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = COLUMN_DEPARTMENT_ID)
    private Integer deptId;

    @Column(name = COLUMN_DEPARTMENT_NAME, columnDefinition = "VARCHAR(255)")
    private String deptName;

//Getter setter
}

服务Impl类(商业逻辑)

public void save(User user) {

    if(user.getDept()!=null)
    {
        Department dept = deptRepo.findOne(user.getDept().getDeptId());
        if(dept==null)
        {
            dept = deptRepo.save(user.getDept());
        }
        user.setDept(dept);
    }
    UserRepository.save(user);  

    }

2 个答案:

答案 0 :(得分:0)

文档说CascadeType.ALL等同于

cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}.

您只能选择您真正想要使用的类型,例如:

@Cascade(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})

遵循文件: https://docs.oracle.com/javaee/6/api/javax/persistence/CascadeType.html

答案 1 :(得分:0)

您很可能会传递已在已关闭的交易中获取的实体:

public void save(User user)

尝试首先合并传递的用户,然后处理结果:

mergedUser = UserRepository.merge(user) // calls session.merge(user) inside

if(mergedUser .getDept()!=null)
{
    Department dept = deptRepo.findOne(mergedUser .getDept().getDeptId());
    if(dept==null)
    ...