package com.cn; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.SQLException;
import org.hibernate.Hibernate; 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;
public class Test { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init(){ Configuration config=new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); //创建会话工厂对象 sessionFactory=config.buildSessionFactory(serviceRegistry); //会话对象 session=sessionFactory.openSession(); //启动事物 transaction= session.beginTransaction();
}
@After
public void destory(){
transaction.commit();
session.close();
sessionFactory.close();
}
@org.junit.Test
public void test() {
Students s =new Students("16","12");
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
connection.setAutoCommit(true);
}
});
Address address=new Address("12","45");
s.setAddress(address);
session.save(s);
//把sql语句输出
session.flush();
}
@org.junit.Test
public void QuryStudent(){
Students s=(Students) session.get(Students.class,"16");
System.out.println(s);
}
@org.junit.Test
public void updateStudent(){
Students s=(Students) session.get(Students.class,"16");
s.setPass("55");
session.update(s);
}
@org.junit.Test
public void deleteStudent(){
Students s=(Students) session.get(Students.class,"16");
session.delete(s);;
}
可以上面的get处换为load get方法立即执行 load方法是执行时调用 load返回的是代理对象 get查询空返回null load没有返回,报Object错误