protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User u1 = new User(); u1.setName("测试11111"); User u2 = new User(); u2.setName("测试222222"); new SaveService().add(u1, u2); System.out.println("ok"); }
配置:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetransaction</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 将session绑定到当前的线程中,这样在同一个线程中就可以使用同一个session,进行事务操作,要是用全称 --> <property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property> <mapping resource="com/gordon/domain/User.hbm.xml"/> </session-factory> </hibernate-configuration>
package com.gordon.service; import org.hibernate.Session; import org.hibernate.Transaction; import com.gordon.dao.SaveDao; import com.gordon.domain.User; import com.gordon.utils.HibernateUtil; public class SaveService { public void add(User u1, User u2) { SaveDao saveDao = new SaveDao(); // 从当前线程中获取session Session session = HibernateUtil.getCurrentSession(); //开启这个session的事务 Transaction tr = session.beginTransaction(); try { saveDao.add1(u1); int i = 100/0; saveDao.add2(u2); tr.commit(); } catch (Exception e) { tr.rollback(); e.printStackTrace(); } // 不需要关闭session,会自动关闭 } }
package com.gordon.dao; import org.hibernate.Session; import com.gordon.domain.User; import com.gordon.utils.HibernateUtil; public class SaveDao { public void add1(User u) { Session session = HibernateUtil.getCurrentSession(); session.save(u); } public void add2(User u) { Session session = HibernateUtil.getCurrentSession(); session.save(u); } }
package com.gordon.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final Configuration CONFIGURATION; private static final SessionFactory SESSIONFACTORY; static { CONFIGURATION = new Configuration().configure(); SESSIONFACTORY = CONFIGURATION.buildSessionFactory(); }; public static Session getSession() { return SESSIONFACTORY.openSession(); } public static Session getCurrentSession() { return SESSIONFACTORY.getCurrentSession(); } }