1 hibernate是非自动提交。如果transaction不写的话,会只创建表结构而不插入语句。
如果不写transaction而想实现插入的功能的话,需要重写session的dowork方法(记得flush)。
2 demo:
package hibernate_001;
import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.Date; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import java.util.concurrent.Executor;
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.jdbc.Work; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test;
import com.ddwei.student.Student; import com.mysql.jdbc.Connection; import com.mysql.jdbc.ExceptionInterceptor; import com.mysql.jdbc.Extension; import com.mysql.jdbc.MySQLConnection; import com.mysql.jdbc.log.Log;
public class StudentTest { private SessionFactory sessionFactory; private Session session; private Transaction trasaction; @Test public void testSaveStudent(){ Student student =new Student(3,"周恩来","男",new Date(),"绍兴");//创建学生对象 session.save(student);//会话保存学生对象进入数据库 } @Before public void init(){ //1 创建配置对象 Configuration config = new Configuration().configure(); //2 创建服务对象 ServiceRegistry serviceRe = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //3 创建会话工厂 sessionFactory = config.buildSessionFactory(serviceRe); //4 打开会话 session = sessionFactory.openSession(); //5 创建事务 // trasaction = session.beginTransaction(); } @After public void destroy(){ // trasaction.commit(); session.doWork(new Work() { @Override public void execute(java.sql.Connection arg0) throws SQLException { // TODO Auto-generated method stub arg0.setAutoCommit(true); } }); session.flush(); session.close(); sessionFactory.close(); }
}