0
点赞
收藏
分享

微信扫一扫

Hibernate 中的attachDirty,attachClean,merge,findByProperty和findByExample


attachDirty:将传入的对象持久化并保存。如果对象未保存(Transient状态),调用save方法保存。如果对象已保存(Detached状态),调用update方法将对象与Session重新关联。

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

attachClean:将传入的对象状态设置为Transient状态。

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

merge:将传入的detached状态的对象的属性复制到持久化对象中,并返回该持久化对象 。如果该session中没有关联的持久化对象,加载一个,如果传入对象未保存,保存一个副本并作为持久对象返回,传入对象依然保持detached状态。

public Addressbook merge(Addressbook detachedInstance) {
log.debug("merging Addressbook instance");
try {
Addressbook result = (Addressbook) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

findByProperty: propertyName指向列明,value对应的值,这样写便于对该表不同字段查询合用一个方法,查询时传入要查的列名和对应的值就可以了,例如HQL查询商品信息的语句如下:
String querysql = “from GoodsInfo as u where u.”+propertyName+” like ‘%”+value+”%’ order by u.goods_price asc”

public List findByProperty(String propertyName, Object value) {
log.debug("finding Addressbook instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Addressbook as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw

findByExample:

public List findByExample(Addressbook instance) {
log.debug("finding Addressbook instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}

举报

相关推荐

0 条评论