日期:2014-05-17 浏览次数:20957 次
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="txManager" />
import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Repository @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class BaseDao<T, PK extends Serializable> implements BaseDaoService<T, PK> { @Resource SessionFactory factory; /** *保存对象 */ @Override @Transactional(readOnly = false, propagation = Propagation.SUPPORTS) public void save(T entity) { factory.getCurrentSession().persist(entity);//persist方法不能插入数据 } }
@Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class MyService { @Resource MyDAO myDAO;//继承自dao基类,此处是dao的接口 @Override @Transactional(readOnly = false, propagation = Propagation.SUPPORTS) public void save(User entity) { myDAO.save(entity); } }
@Controller @RequestMapping(value = "/user") public class UserAction { @Resource UserService myService;//service接口 @RequestMapping(value = "/add") public String user_add(User user) { myService.save(user); return "list"; } }
factory.getCurrentSession().persist(entity);// 把persit更改为 factory.getCurrentSession().save(entity);