---
title: "hibernate中merge()、attachDirty()、attachClean()这三个方法是做什么的？怎么用？"
author: "laoaenna"
date: "2011-12-08T13:46:20Z"
tags: []
categories: ["企业架构"]
slug: "hibernate-merge-attachdirty-attachclean"
draft: false
lastmod: "2011-12-08T13:46:20Z"
id: 1297611
url: "https://laoaenna.iteye.com/blog/1297611"
---

\* 将传入的detached状态的对象的属性复制到持久化对象中，并返回该持久化对象  
\* 如果该session中没有关联的持久化对象，加载一个，如果传入对象未保存，保存一个副本并作为持久对象返回，传入对象依然保持detached状态。  
\* @see com.CodeDepts  
\*/  
public CodeDepts merge(CodeDepts detachedInstance) {  
log.debug("merging CodeDepts instance");  
try {  
CodeDepts result = (CodeDepts) getSession()  
.merge(detachedInstance);  
log.debug("merge successful");  
return result;  
} catch (RuntimeException re) {  
log.error("merge failed", re);  
throw re;  
}  
}

/\**  
\* 将传入的对象持久化并保存。  
\* 如果对象未保存（Transient状态），调用save方法保存。如果对象已保存（Detached状态），调用update方法将对象与Session重新关联。

\* @see com.CodeDepts  
\*/

public void attachDirty(CodeDepts instance) {  
log.debug("attaching dirty CodeDepts instance");  
try {  
getSession().saveOrUpdate(instance);  
log.debug("attach successful");  
} catch (RuntimeException re) {  
log.error("attach failed", re);  
throw re;  
}  
}  
   
 

/\**  
\* 将传入的对象状态设置为Transient状态  
\* @see com.CodeDepts  
\*/

public void attachClean(CodeDepts instance) {  
log.debug("attaching clean CodeDepts instance");  
try {  
getSession().lock(instance, LockMode.NONE);  
log.debug("attach successful");  
} catch (RuntimeException re) {  
log.error("attach failed", re);  
throw re;  
}  
}