Loading

hibernate主配置文件中指定session与当前线程绑定

配置一条属性

<property name="hibernate.current_session_context_class">thread</property>

 

 

dao层 (以下代码仅是演示)

public class CustomerDaoImp implements CustomerDao {

	@Override
	public void save(Customer customer) {
		//1.获取当前线程绑定的session
		Session session = HibernateUtils.getCurrentSession();
	
	        //3.执行保存
		session.save(customer);
	}
}

 service层

public class CustomerServiceImp implements CustomerService {
	private CustomerDao dao=new CustomerDaoImp();
	@Override
	public void save(Customer customer) {
                //获取当前线程绑定的session
		Session session = HibernateUtils.getCurrentSession();
		//开启事务
		Transaction tx = session.beginTransaction();
		
		try {
			dao.save(customer);	
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		}
		//提交事务
		tx.commit();
	}

 

posted @ 2019-03-31 12:41  青岑  阅读(658)  评论(0编辑  收藏  举报