Hibernate学习笔记(二)

本文介绍了Hibernate框架的基本配置,包括核心配置文件hibernate.cfg.xml的常见参数设置,Session对象的作用及常用方法,事务Transaction的基本操作,以及类配置文件hbm.xml的常用配置。

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

 

转载于:https://www.cnblogs.com/sunqian/p/5084459.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值