方法抛出'org.hibernate.PersistentObjectException'异常。分离的实体传递给持久化

时间:2016-01-22 17:11:53

标签: java spring hibernate jpa

我有两个表(即Hibernate中的实体),它们相关:

@Entity
@Table(name = "table_one")
public class TableOne  {

    private int id;
    private String code;
    private String value;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    @Column(name= "code")
    public String getCode() {
        return this.code;
    }

    @Column(name= "value")
    public String getValue() {
        return this.value;
    }
    // setters ignored here
}

----------------------------------------------
@Entity
@Table(name = "table_two")
public class TableTwo {

    private Integer id;
    private TableOne tableOne;
    private String request;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "table_one_id", nullable = false)
    public TableOne getTableOne() {
        return tableOne;
    }

    @Column(name= "request")
    public String getRequest() {
        return this.request;
    }
    // setters ignored here
}

现在,从没有@Transactional注释的方法(或类)中,我调用Service类方法来持久化TableTwo对象。此服务方法已注释@Transactional

// from a normal method with no annotations
service.insert(tableTwo);
----------------------------
public class MyService {

    @Autowired
    private MyDao dao;

    @Transactional
    public void insert(TableTwo tableTwo){
        dao.insert(tableTwo);
    }
}
------------------------------
public class MyDao {
    public void insert(TableTwo tableTwo){
      sessionFactory.getCurrentSession().persist(tableTwo.getTableOne());
      sessionFactory.getCurrentSession().persist(tabletwo);
    }
}

这在调试中给出了以下异常:

Method threw 'org.hibernate.PersistentObjectException' exception.
detached entity passed to persist: org.project.TableOne

这里有什么问题?我将TableOne内的TableTwo的瞬态对象转换为持久状态,然后持久化TableTwo对象。我怎么能纠正这个?如果可能的话,是否可以通过注释来实现?

每次持久TableOne对象时,我都不希望持久化TableTwo对象。如果可能的话,我只想这样做:

tableTwo.setTableOne(new TableOne(id));
dao.persist(tableTwo);

2 个答案:

答案 0 :(得分:1)

尝试拨打saveOrUpdate而不是persist persist操作适用于全新的临时对象,如果已分配id,则操作失败。

答案 1 :(得分:1)

我看到您从服务类获取tableOne对象,即TableOne tableOne = service.getTableOneById(id);

所以,我相信数据库中已经存在tableOne记录,因此无需在你的dao insert(...)方法中再次保留它。

您可以删除sessionFactory.getCurrentSession().persist(tableTwo.getTableOne());,因为您没有对tableOne对象进行任何更改。

如果您对需要保留的tableOne对象进行了任何更改,请考虑使用合并方法,即sessionFactory.getCurrentSession().merge(tableTwo.getTableOne());

相关问题