Hibernate:如何处理“保存”数据库中可能存在或可能不存在的瞬态对象

时间:2012-02-24 14:02:42

标签: hibernate transient

这是一个关于持久存在我的数据库中可能存在的瞬态对象的Hibernate问题。

给定一个瞬态对象(Id为空),我的数据库中可能已经存在,也可能没有,并且还有一个唯一的列(即我的业务主键,用'unique = true'注释)。我如何尝试保存它而不存在获得错误的风险:完整性约束违规:唯一约束或索引违规

在尝试保留对象之前,我是否应该提供检查数据库重复项的方法?这有点令人沮丧。

这是我尝试保存两个相同的瞬态对象的测试...

这是我的目标:

@Entity
public class ArchivedLicence extends DomainObject implements Licence {
    private static final long serialVersionUID = 84973741L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;


    @Column (unique=true, nullable=false)
    private String md5Hash;

    @Override
    public boolean equals(Object o) {
        if(o instanceof ArchivedLicence) {
            return md5Hash.equals(((ArchivedLicence)o).md5Hash);
        }
        return super.equals(o);
    }
    ...

以下是我的数据访问对象中的保存方法:

    @Transactional
    @Override
    public void saveOrUpdate(ArchivedLicence archivedLicence) {

        getCurrentSession().saveOrUpdate(archivedLicence);
        //getCurrentSession().save(archivedLicence);
    }

这是我的测试:

        //Given the first ArchivedLicence
        ArchivedLicence archivedLicence1 = null;
        try {
            archivedLicence1 = new ArchivedLicence(licenceDao.getByName(internalLicenceName));
        } catch (IOException ex) {
            Logger.getLogger(OrderTest.class.getName()).log(Level.SEVERE, null, ex);
        }

        //When it is persisted
        archivedLicenceDao.saveOrUpdate(archivedLicence1);
        flush();

        //Then there should be one ArchivedLicence in the the database
        assertEquals(new Long(1), archivedLicenceDao.countAll());

        //When a second identical ArchiviedLicence is persisted
        ArchivedLicence archivedLicence2 = null;
        try {
            archivedLicence2 = new ArchivedLicence(licenceDao.getByName(internalLicenceName));
        } catch (IOException ex) {
            Logger.getLogger(OrderTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        archivedLicenceDao.saveOrUpdate(archivedLicence2);
        flush();

        //Then there should still only be one ArchivedLicence in the database
        assertEquals(new Long(1), archivedLicenceDao.countAll());

任何帮助表示感谢,谢谢,Jon

1 个答案:

答案 0 :(得分:1)

不幸的是,您将不得不查询数据库以查看对象是否存在,然后更新它,如果不存在则保存新对象。

saveOrUpdate不是为了这个目的 - 它的作用是检查内存中对象的id,如果id为null则调用save,如果id不为null则更新。