使用MyEclipse中用hibernate反向工程生成的DAO会发生对象无法存储到数据库的现象,原因是没有运用事务。DAO里注释提示如下:
/**
* A data access object (DAO) providing persistence and search support for User
* entities. Transaction control of the save(), update() and delete() operations
* can directly support Spring container-managed transactions or they can be
* augmented to handle user-managed Spring transactions. Each of these methods
* provides additional information for how to configure it for the desired type
* of transaction control.
*
* @see org.hibernate.entity.User
* @author MyEclipse Persistence Tools
*/
解决方法一、使用Spring的事务管理
方法二、修改DAO,添加事务处理
当然可以在调用dao对象的代码前后加事务控制,但这样破坏了dao对数据库操作的封装,让业务层中掺杂了持久层代码。所以进行以下修改:
import org.hibernate.Session;
import org.hibernate.Transaction;
public void save(Resource transientInstance) {
log.debug("saving Resource instance");
try {
Session session = getSession();
Transaction tr = session.beginTransaction(); //开始事务
session.save(transientInstance);
tr.commit(); //提交事务
session.flush(); //清空缓存
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Resource persistentInstance) {
log.debug("deleting Resource instance");
try {
Session session = getSession();
Transaction tr = session.beginTransaction();
session.delete(persistentInstance);
tr.commit();
session.flush();
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}