报错javax.persistence.TransactionRequiredException: no transaction is in progress at org.hibernate.internal.SessionImpl.checkTransactionNeeded(SessionImpl.java:3392) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1385) at junit.StudentTest.
package junit; import java.sql.Connection; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.model.Student; public class StudentTest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init() { Configuration configure = new Configuration().configure(); //ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() // .applySettings(configure.getProperties()).build(); sessionFactory = configure.buildSessionFactory(); session = sessionFactory.openSession(); //transaction = session.beginTransaction(); } @Test public void testSaveStudent() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = sdf.parse("1987-03-31"); Student s = new Student(3, "aa", date, "上海"); session.doWork(new Work() { @Override public void execute(Connection arg0) throws SQLException { // TODO Auto-generated method stub arg0.setAutoCommit(true); } }); session.save(s); session.flush(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @After public void destroy() { //transaction.commit(); session.close(); sessionFactory.close(); } }
使用dowork方法不成功,报错no tranction in progress