Hibernate存储指定identifier的entity

在调用save(),saveOrUpdate(),persist()等操作时,如果entity中已经有了identifier,仍然会根据identifier的生成策略重新生成一个。这样会导致存储的identifier 与指定只不同的情况。 参考hibernate文档
为解决此问题,可以使用replicate() 代替,在Hibernate的javaDoc中的说明为

replicate

void replicate(Object object,
    ReplicationMode replicationMode)
          throws HibernateException

Persist the state of the given detached instance, reusing the current identifier value. This operation cascades >to associated instances if the association is mapped with cascade=\”replicate\”.
Parameters:
object – a detached instance of a persistent class
Throws:
HibernateException

其中模式的javaDoc

org.hibernate
Class ReplicationMode

static ReplicationMode    EXCEPTION 
      Throw an exception when a row already exists.
static ReplicationMode    IGNORE 
      Ignore replicated entities when a row already exists.
static ReplicationMode    LATEST_VERSION 
      When a row already exists, choose the latest version.
static ReplicationMode    OVERWRITE 
      Overwrite existing rows when a row already exists. 

所以如果需要指定identifier只需要使用replicate() 即可.下面给出一种保存带有identifier信息的save()

function  save(T entity){
    getSession().replicate(entity,ReplicationMode.OVERWRITE);//此处如已有记录则覆盖Overwrite existing rows when a row already exists. 
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.