封装Util获取session工厂
采用单例模式(保证外部调用的方法中不包含new操作,new操作只执行一次,比如让它随着类的加载而执行)
public class HibernateUtil { //静态域,随着类的加载而加载;类的所有实例共享一个sqlSessionFactory,一个对象对其修改则所有对象的该域都被修改。常量,调用对象构造器初始化后不能更改 private static final SessionFactory sessionFactory=buildSessionFactory(); private static SessionFactory buildSessionFactory() { Configuration configuration=new Configuration().configure(); ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); } //这样获取的就都是单例了 public static SessionFactory getSessionFactory() { return sessionFactory; } }
Crud
public class StudentTest {
private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
private void add() {
Session session=sessionFactory.openSession(); session.beginTransaction(); Student s=new Student(); s.setName("李四"); session.save(s); session.getTransaction().commit(); session.close();
}
private void delete() {
Session session=sessionFactory.openSession(); session.beginTransaction(); Student s=(Student)session.get(Student.class, Long.valueOf(1)); session.delete(s); session.getTransaction().commit(); session.close();
}
private void update() {
Session session=sessionFactory.openSession(); session.beginTransaction(); Student s=(Student)session.get(Student.class, Long.valueOf(1)); s.setName("张三2"); session.save(s); session.getTransaction().commit(); session.close();
}
private void getAllStudent() {
Session session=sessionFactory.openSession(); session.beginTransaction(); String hql="from Student"; Query query=session.createQuery(hql); List<Student> studentList=query.list(); for(Student s:studentList) { System.out.println(s); } session.getTransaction().commit(); session.close();
}
public static void main(String[] args) {
StudentTest studentTest=new StudentTest(); //studentTest.add(); //studentTest.delete(); //studentTest.update(); studentTest.getAllStudent();
}
}session缓存
查询某条数据都是先到session缓存中查看是否存在,存在即引用,不存在再去数据库查询
Student s1=(Student)session.get(Student.class, Long.valueOf(1)); //select语句查询 Student s2=(Student)session.get(Student.class, Long.valueOf(2)); Student s3=(Student)session.get(Student.class, Long.valueOf(1)); //在session缓存中获取 System.out.println(s1==s2); //false System.out.println(s1==s3); //true
代码实例
- eclipse->HibernateCrud