• Hibernate学习笔记(二)


    1.Hibernate.cfg.xml常用配置
      hibernate.show_sql   是否把Hibernate运行时的sql语句输出到控制台,值true、false
      hibernate.format_sql 输出到控制台的sql语句是否格式化,值true、false
      hbm2ddl.auto   sql语句生成策略,值create、update、create-dorp、validate
      hibernate.default_schema 默认的数据库
      hibernate.dialect 配置数据库方言,可以优化sql语句。

    2.Session对象简介

    类似于jdbc的Connection,但Hibernate不建议使用Connection连接数据库。下图是Hibernate执行流程:

    Session和Connection是多对一的关系,一个连接可以有多个会话。session常用方法有sava(),update(),delete(),createQuery(),

    3.事务Transaction

    Hibernate对数据库的操作都是封装在transaction中,并且默认都是费自动提交的。保存数据必须提交事务。可以通过session.doWork()设置自动提交,但并不推荐这么做!

    @Test
        public void testSaveStudent(){
            Students s=new Students(1,"张三丰","男",new Date(),"武当山");
            session.doWork(new Work(){
    
                @Override
                public void execute(Connection connection) throws SQLException {
                    connection.setAutoCommit(true);
                }
                
            });
            session.save(s);
            session.flush();//一定要有刷新会话的操作,sql才会立即执行
        }

    4.Session详解

    获取session的两种方法:

    这张图中需要强调的是使用getCurrentSession()必须在Hibernate.cfg.xml中进行配置参数!

    getCurrentSession()和openSession()的区别

    1)getCurrentSession()在事务提交或回滚后都会自动关闭,而openSession()需要手动关闭,如果多次不关闭会造成数据库连接池溢出。

    试验方法:testOpenSession()、testGetCurrentSession()

    2)getCurrentSession()是得到现有的Session,openSession()每次创建新的Session。

    试验方法:testSavaStudentWithOpenSession()、testSavaStudentWithGetCurrentSession()。见如下代码:

    import java.sql.Connection;
    import java.sql.SQLException;
    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.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    import org.junit.Test;
    
    public class SessionTest {
        @Test
        public void testOpenSession() {
            // 获取参数配置对象
            Configuration config = new Configuration().configure();
            // 获取服务注册对象
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                    .applySettings(config.getProperties()).buildServiceRegistry();
            // 得到SessionFactory对象
            SessionFactory sessionFactory = config
                    .buildSessionFactory(serviceRegistry);
            // session对象创建
            Session session = sessionFactory.openSession();
            Session session2 = sessionFactory.openSession();
            if (session == session2)
                System.out.println("这是同一个session对象");
            else
                System.out.println("这是不同的session对象");
            if (session != null) {
                System.out.println("session创建成功!");
            } else {
                System.out.println("session创建失败!");
            }
        }
    
        @Test
        public void testGetCurrentSession() {
            Configuration config = new Configuration().configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                    .applySettings(config.getProperties()).buildServiceRegistry();
            SessionFactory sessionFactory = config
                    .buildSessionFactory(serviceRegistry);
            Session session = sessionFactory.getCurrentSession();
            Session session2 = sessionFactory.getCurrentSession();
            System.out.println(session == session2);
            if (session != null) {
                System.out.println("session创建成功!");
            } else {
                System.out.println("session创建失败!");
            }
        }
    
        @Test
        public void testSavaStudentWithOpenSession() {
            Configuration config = new Configuration().configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                    .applySettings(config.getProperties()).buildServiceRegistry();
            SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
            Session session1=sessionFactory.openSession();
            Transaction transaction=session1.beginTransaction();
            Students s=new Students(1,"张三丰","男",new Date(),"武当山");
            session1.doWork(new Work(){
    
                @Override
                public void execute(Connection connection) throws SQLException {
                    System.out.println("connection hashcode:"+connection.hashCode());
                }
                
            });
            session1.save(s);
            transaction.commit();
            
            Session session2=sessionFactory.openSession();
            transaction=session2.beginTransaction();
            s=new Students(2,"孙中山","男",new Date(),"香港");
            session2.doWork(new Work(){
    
                @Override
                public void execute(Connection connection) throws SQLException {
                    System.out.println("connection hashcode:"+connection.hashCode());
                }
                
            });
            session2.save(s);
            transaction.commit();
        }
        @Test
        public void testSavaStudentWithGetCurrentSession() {
            Configuration config = new Configuration().configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                    .applySettings(config.getProperties()).buildServiceRegistry();
            SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
            Session session1=sessionFactory.getCurrentSession();
            Transaction transaction=session1.beginTransaction();
            Students s=new Students(1,"张三丰","男",new Date(),"武当山");
            session1.doWork(new Work(){
    
                @Override
                public void execute(Connection connection) throws SQLException {
                    System.out.println("connection hashcode:"+connection.hashCode());
                }
                
            });
            session1.save(s);
            transaction.commit();
            
            Session session2=sessionFactory.getCurrentSession();
            transaction=session2.beginTransaction();
            s=new Students(2,"孙中山","男",new Date(),"香港");
            session2.doWork(new Work(){
    
                @Override
                public void execute(Connection connection) throws SQLException {
                    System.out.println("connection hashcode:"+connection.hashCode());
                }
                
            });
            session2.save(s);
            transaction.commit();
        }
    }


    5.类配置文件hbm.xml常用配置:此地址

    http://www.imooc.com/video/7718

  • 相关阅读:
    spring缓存笔记 半注解版
    乐优商城项目视频及源码
    spring cloud Eureka
    idea+maven搭建ssh,支持事务,无hibernate文件整合
    BUU->CRYPTO 知识点分类
    file-upl0ad
    [RoarCTF 2019]Simple Upload
    BUU UPLOAD COURSE 1
    [GXYCTF2019]Ping Ping Ping
    [SWPU2019]Web1
  • 原文地址:https://www.cnblogs.com/sunqian/p/5084459.html
Copyright © 2020-2023  润新知