1.前言

  hibernate与mybatis的位置一样,都是属于DAO层的框架,代替我们原来的JDBC操作数据库,属于ORM(object relationg mapping. 对象关系映射)框架。ORM分为四级,hibernate属于4级:完全面向对象操作数据库,mybatis属于2级,半自动化的ORM框架,dbutils属于1级。

2.使用hibernate的好处

   操作数据库的时候,可以以面向对象的方式来完成.不需要书写SQL语句

3.搭建开发环境

1.导包:

如果没有maven依赖的话需要导入hibernate下required目录下的包。

或者直接采用maven项目,导入maven包地址如下:

  1. <dependency>
  2. <groupId>org.hibernate</groupId>
  3. <artifactId>hibernate-core</artifactId>
  4. <version>5.0.7.Final</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. <version>5.1.37</version>
  10. </dependency>

2..创建数据库表:

  1. CREATE TABLE `cst_customer` (
  2. `cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  3. `cust_name` VARCHAR(32) NOT NULL COMMENT '客户名称(公司名称)',
  4. `cust_user_id` BIGINT(32) DEFAULT NULL COMMENT '负责人id',
  5. `cust_create_id` BIGINT(32) DEFAULT NULL COMMENT '创建人id',
  6. `cust_source` VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源',
  7. `cust_industry` VARCHAR(32) DEFAULT NULL COMMENT '客户所属行业',
  8. `cust_level` VARCHAR(32) DEFAULT NULL COMMENT '客户级别',
  9. `cust_linkman` VARCHAR(64) DEFAULT NULL COMMENT '联系人',
  10. `cust_phone` VARCHAR(64) DEFAULT NULL COMMENT '固定电话',
  11. `cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT '移动电话',
  12. PRIMARY KEY (`cust_id`)
  13. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

3.准备orm元数据

结构

Customer.java

  1. package cn.qlq.domain;
  2.  
  3. public class Customer {
  4.  
  5. /*
  6. * CREATE TABLE `cst_customer` (
  7. `cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  8. `cust_name` VARCHAR(32) NOT NULL COMMENT '客户名称(公司名称)',
  9. `cust_source` VARCHAR(32) DEFAULT NULL COMMENT '客户信息来源',
  10. `cust_industry` VARCHAR(32) DEFAULT NULL COMMENT '客户所属行业',
  11. `cust_level` VARCHAR(32) DEFAULT NULL COMMENT '客户级别',
  12. `cust_linkman` VARCHAR(64) DEFAULT NULL COMMENT '联系人',
  13. `cust_phone` VARCHAR(64) DEFAULT NULL COMMENT '固定电话',
  14. `cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT '移动电话',
  15. PRIMARY KEY (`cust_id`)
  16. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  17. */
  18. private Long cust_id;
  19.  
  20. private String cust_name;
  21. private String cust_source;
  22. private String cust_industry;
  23. private String cust_level;
  24. private String cust_linkman;
  25. private String cust_phone;
  26. private String cust_mobile;
  27. public Long getCust_id() {
  28. return cust_id;
  29. }
  30. public void setCust_id(Long cust_id) {
  31. this.cust_id = cust_id;
  32. }
  33. public String getCust_name() {
  34. return cust_name;
  35. }
  36. public void setCust_name(String cust_name) {
  37. this.cust_name = cust_name;
  38. }
  39. public String getCust_source() {
  40. return cust_source;
  41. }
  42. public void setCust_source(String cust_source) {
  43. this.cust_source = cust_source;
  44. }
  45. public String getCust_industry() {
  46. return cust_industry;
  47. }
  48. public void setCust_industry(String cust_industry) {
  49. this.cust_industry = cust_industry;
  50. }
  51. public String getCust_level() {
  52. return cust_level;
  53. }
  54. public void setCust_level(String cust_level) {
  55. this.cust_level = cust_level;
  56. }
  57. public String getCust_linkman() {
  58. return cust_linkman;
  59. }
  60. public void setCust_linkman(String cust_linkman) {
  61. this.cust_linkman = cust_linkman;
  62. }
  63. public String getCust_phone() {
  64. return cust_phone;
  65. }
  66. public void setCust_phone(String cust_phone) {
  67. this.cust_phone = cust_phone;
  68. }
  69. public String getCust_mobile() {
  70. return cust_mobile;
  71. }
  72. public void setCust_mobile(String cust_mobile) {
  73. this.cust_mobile = cust_mobile;
  74. }
  75. @Override
  76. public String toString() {
  77. return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + "]";
  78. }
  79.  
  80. }

Customer.hbm.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
  5. <!-- 配置表与实体对象的关系 -->
  6. <!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
  7. <hibernate-mapping package="cn.qlq.domain" >
  8. <!--
  9. class元素: 配置实体与表的对应关系的
  10. name: 完整类名
  11. table:数据库表名
  12. -->
  13. <class name="Customer" table="cst_customer" >
  14. <!-- id元素:配置主键映射的属性
  15. name: 填写主键对应属性名
  16. column(可选): 填写表中的主键列名.默认值:列名会默认使用属性名
  17. type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
  18. 每个类型有三种填法: java类型|hibernate类型|数据库类型
  19. not-null(可选):配置该属性(列)是否不能为空. 默认值:false
  20. length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
  21. -->
  22. <id name="cust_id" >
  23. <!-- generator:主键生成策略 -->
  24. <generator class="native"></generator>
  25. </id>
  26. <!-- property元素:除id之外的普通属性映射
  27. name: 填写属性名
  28. column(可选): 填写列名
  29. type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
  30. 每个类型有三种填法: java类型|hibernate类型|数据库类型
  31. not-null(可选):配置该属性(列)是否不能为空. 默认值:false
  32. length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
  33. -->
  34. <property name="cust_name" column="cust_name" >
  35. <!-- <column name="cust_name" sql-type="varchar" ></column> -->
  36. </property>
  37. <property name="cust_source" column="cust_source" ></property>
  38. <property name="cust_industry" column="cust_industry" ></property>
  39. <property name="cust_level" column="cust_level" ></property>
  40. <property name="cust_linkman" column="cust_linkman" ></property>
  41. <property name="cust_phone" column="cust_phone" ></property>
  42. <property name="cust_mobile" column="cust_mobile" ></property>
  43. </class>
  44. </hibernate-mapping>

4.classpath目录下编写hibernate.cfg.xml文件(或者hibernate.properties文件,两者作用一样,早期版本你的hibernate采用properties文件进行配置,目前采用xml进行配置)

例如我们采用hibernate.cfg.xml配置文件: (头引入的是3.0.dtd是为了兼容旧版本,有时候这个会有区别)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5. <hibernate-configuration>
  6. <session-factory>
  7.  
  8. <!--
  9. #hibernate.dialect org.hibernate.dialect.MySQLDialect
  10. #hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
  11. #hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
  12. #hibernate.connection.driver_class com.mysql.jdbc.Driver
  13. #hibernate.connection.url jdbc:mysql:///test
  14. #hibernate.connection.username gavin
  15. #hibernate.connection.password
  16. -->
  17. <!-- 数据库驱动 -->
  18. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  19. <!-- 数据库url -->
  20. <property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
  21. <!-- 数据库连接用户名 -->
  22. <property name="hibernate.connection.username">sa</property>
  23. <!-- 数据库连接密码 -->
  24. <property name="hibernate.connection.password">123456</property>
  25. <!-- 数据库方言
  26. 不同的数据库中,sql语法略有区别. 指定方言可以让hibernate框架在生成sql语句时.针对数据库的方言生成.
  27. sql99标准: DDL 定义语言 库表的增删改查
  28. DCL 控制语言 事务 权限
  29. DML 操纵语言 增删改查
  30. 注意: MYSQL在选择方言时,请选择最短的方言.
  31. -->
  32. <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  33.  
  34. <!-- #hibernate.show_sql true
  35. #hibernate.format_sql true
  36. -->
  37. <!-- 将hibernate生成的sql语句打印到控制台 -->
  38. <property name="hibernate.show_sql">true</property>
  39. <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
  40. <property name="hibernate.format_sql">true</property>
  41. <!--
  42. ## auto schema export 自动导出表结构. 自动建表
  43. #hibernate.hbm2ddl.auto create 自动建表.每次框架运行都会创建新的表.以前表将会被覆盖,表数据会丢失.(开发环境中测试使用)
  44. #hibernate.hbm2ddl.auto create-drop 自动建表.每次框架运行结束都会将所有表删除.(开发环境中测试使用)
  45. #hibernate.hbm2ddl.auto update(推荐使用) 自动生成表.如果已经存在不会再生成.如果表有变动.自动更新表(不会删除任何数据).
  46. #hibernate.hbm2ddl.auto validate 校验.不自动生成表.每次启动会校验数据库中表是否正确.校验失败.
  47. -->
  48. <property name="hibernate.hbm2ddl.auto">update</property>
  49. <!-- 引入orm元数据
  50. 路径书写: 填写src下的路径
  51. -->
  52. <mapping resource="cn/qlq/domain/Customer.hbm.xml" />
  53.  
  54. </session-factory>
  55. </hibernate-configuration>

必选配置
  4+1 方言
可选配置
  显示sql
  格式化sql
  自动生成表
    |- update
orm元数据引入
  <mapping resource="" />

补充:

jdbc:mysql:///company   等同于    jdbc:mysql://localhost:3306/company company

     指的是数据库名称也就是说第三个'/'代表 'localhost:3306/'

"/"其实就是说从根目录开始的意思。

4.书写代码进行测试

1.测试构建会话工厂  (如果表不存在会自动创建表)

  1. package cn.qlq.util;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.boot.MetadataSources;
  5. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  6. import org.hibernate.service.ServiceRegistry;
  7.  
  8. public class Test {
  9.  
  10. public static void main(String[] args) {
  11. //3.3以及之前的版本构建会话工厂对象
  12. // SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  13.  
  14. //5.0之后获取SessionFactory
  15. //创建服务注册对象
  16. ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
  17. SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
  18.  
  19. System.out.println(sessionFactory);
  20. }
  21.  
  22. }

日志信息:

  1. 七月 18, 2018 11:58:34 下午 org.hibernate.Version logVersion
  2. INFO: HHH000412: Hibernate Core {5.0.7.Final}
  3. 七月 18, 2018 11:58:34 下午 org.hibernate.cfg.Environment <clinit>
  4. INFO: HHH000206: hibernate.properties not found
  5. 七月 18, 2018 11:58:34 下午 org.hibernate.cfg.Environment buildBytecodeProvider
  6. INFO: HHH000021: Bytecode provider name : javassist
  7. 七月 18, 2018 11:58:35 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
  8. INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
  9. 七月 18, 2018 11:58:39 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
  10. WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
  11. 七月 18, 2018 11:58:39 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  12. INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql:///hibernate]
  13. 七月 18, 2018 11:58:39 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  14. INFO: HHH10001001: Connection properties: {user=sa, password=****}
  15. 七月 18, 2018 11:58:39 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  16. INFO: HHH10001003: Autocommit mode: false
  17. 七月 18, 2018 11:58:39 下午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
  18. INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
  19. 七月 18, 2018 11:58:40 下午 org.hibernate.dialect.Dialect <init>
  20. INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
  21. 七月 18, 2018 11:58:41 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
  22. INFO: HHH000228: Running hbm2ddl schema update
  23. org.hibernate.internal.SessionFactoryImpl@4e38854
  24. 1

2.测试保存数据

  注意:

  获取会话工厂可以用3.0或者5.0获取会话工厂的方法,但是不可以用4.0获取的方法,会报错Unknown entity: cn.qlq.domain.Customer。

  也就是5.0兼容3.0版本的获取活化工厂的方式。

  1. package cn.qlq.util;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.hibernate.boot.MetadataSources;
  7. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  8. import org.hibernate.service.ServiceRegistry;
  9.  
  10. import cn.qlq.domain.Customer;
  11.  
  12. public class Test {
  13.  
  14. public static void main(String[] args) {
  15. //3.3以及之前的版本构建会话工厂对象
  16. // SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  17.  
  18. //5.0之后获取SessionFactory
  19. //创建服务注册对象
  20. ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
  21. //创建会话工厂对象
  22. SessionFactory sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
  23.  
  24. //获取session对象
  25. Session session = sessionFactory.openSession();
  26. //开启事务
  27. Transaction tx = session.beginTransaction();
  28. //保存对象
  29. Customer customer = new Customer();
  30. customer.setCust_name("测试名称222");
  31. session.save(customer);
  32. tx.commit();
  33. //关闭流
  34. session.close();
  35. sessionFactory.close();
  36. }
  37.  
  38. }

结果:

  1. 七月 19, 2018 12:18:33 上午 org.hibernate.Version logVersion
  2. INFO: HHH000412: Hibernate Core {5.0.7.Final}
  3. 七月 19, 2018 12:18:33 上午 org.hibernate.cfg.Environment <clinit>
  4. INFO: HHH000206: hibernate.properties not found
  5. 七月 19, 2018 12:18:33 上午 org.hibernate.cfg.Environment buildBytecodeProvider
  6. INFO: HHH000021: Bytecode provider name : javassist
  7. 七月 19, 2018 12:18:34 上午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
  8. INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
  9. 七月 19, 2018 12:18:38 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
  10. WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
  11. 七月 19, 2018 12:18:38 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  12. INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql:///hibernate]
  13. 七月 19, 2018 12:18:38 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  14. INFO: HHH10001001: Connection properties: {user=sa, password=****}
  15. 七月 19, 2018 12:18:38 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  16. INFO: HHH10001003: Autocommit mode: false
  17. 七月 19, 2018 12:18:38 上午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
  18. INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
  19. 七月 19, 2018 12:18:39 上午 org.hibernate.dialect.Dialect <init>
  20. INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
  21. 七月 19, 2018 12:18:41 上午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
  22. INFO: HHH000228: Running hbm2ddl schema update
  23. Hibernate:
  24. insert
  25. into
  26. cst_customer
  27. (cust_name, cust_source, cust_industry, cust_level, cust_linkman, cust_phone, cust_mobile)
  28. values
  29. (?, ?, ?, ?, ?, ?, ?)
  30. 七月 19, 2018 12:18:42 上午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
  31. INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql:///hibernate]

至此,采用hibernate实现了简单的添加。

5.API解释:

Configuration 读取配置
sessionFactory 创建session
Session 获得事务操作对象,以及数据增删改查
Transaction 控制事务.

  • Configuration对象
  1. package cn.itheima.b_api;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.hibernate.cfg.Configuration;
  7. import org.junit.Test;
  8.  
  9. import cn.itheima.domain.Customer;
  10.  
  11. //学习Configuration对象
  12. // Configuration功能: 配置加载类.用于加载主配置文件,orm元数据加载
  13. public class Demo {
  14.  
  15. @Test
  16. public void fun1(){
  17. //1 创建,调用空参构造
  18. Configuration conf = new Configuration();
  19. //2 读取指定主配置文件 => 空参加载方法,加载src下的hibernate.cfg.xml文件
  20. conf.configure();
  21. //3 读取指定orm元数据(扩展),如果主配置中已经引入映射配置.不需要手动加载
  22. //conf.addResource(resourceName);
  23. //conf.addClass(persistentClass);
  24.  
  25. //4 根据配置信息,创建 SessionFactory对象
  26. SessionFactory sf = conf.buildSessionFactory();
  27.  
  28. }
  29. }
  • SessionFactory详解(一个web项目要保证一个SessionFactory,单例模式)
  1. package cn.itheima.b_api;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.hibernate.cfg.Configuration;
  7. import org.junit.Test;
  8.  
  9. import cn.itheima.domain.Customer;
  10.  
  11. //学习SessionFactory对象
  12. // SessionFactory功能: 用于创建操作数据库核心对象session对象的工厂.
  13. // 简单说功能就一个---创建session对象
  14. //注意:1.sessionfactory 负责保存和使用所有配置信息.消耗内存资源非常大.
  15. // 2.sessionFactory属于线程安全的对象设计.
  16. //结论: 保证在web项目中,只创建一个sessionFactory.
  17. public class Demo2 {
  18.  
  19. @Test
  20. public void fun1(){
  21. //1 创建,调用空参构造
  22. Configuration conf = new Configuration();
  23. //2 读取指定主配置文件 => 空参加载方法,加载src下的hibernate.cfg.xml文件
  24. conf.configure();
  25. //3 读取指定orm元数据(扩展),如果主配置中已经引入映射配置.不需要手动加载
  26. //conf.addResource(resourceName);
  27. //conf.addClass(persistentClass);
  28.  
  29. //4 根据配置信息,创建 SessionFactory对象
  30. SessionFactory sf = conf.buildSessionFactory();
  31. //--------------------------------------------------
  32. //5 获得session
  33. //打开一个新的session对象
  34. sf.openSession();
  35. //获得一个与线程绑定的session对象
  36. sf.getCurrentSession();
  37. }
  38. }
  • Session对象
  1. package cn.itheima.b_api;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.Transaction;
  6. import org.hibernate.cfg.Configuration;
  7. import org.junit.Test;
  8.  
  9. import cn.itheima.domain.Customer;
  10.  
  11. //学习Session对象
  12. //session对象功能: 表达hibernate框架与数据库之间的连接(会话).session类似于
  13. // JDBC年代的connection对象. 还可以完成对数据库中数据的增删改查操作.
  14. // session是hibernate操作数据库的核心对象
  15. public class Demo3 {
  16.  
  17. @Test
  18. //事务操作
  19. public void fun1(){
  20. //1 创建,调用空参构造
  21. Configuration conf = new Configuration().configure();
  22. //2 根据配置信息,创建 SessionFactory对象
  23. SessionFactory sf = conf.buildSessionFactory();
  24. //3 获得session
  25. Session session = sf.openSession();
  26. //4 session获得操作事务的Transaction对象
  27. //获得操作事务的tx对象
  28. //Transaction tx = session.getTransaction();
  29. //开启事务并获得操作事务的tx对象(建议使用)
  30. Transaction tx2 = session.beginTransaction();
  31. //----------------------------------------------
  32.  
  33. //----------------------------------------------
  34. tx2.commit();//提交事务
  35. tx2.rollback();//回滚事务
  36. session.close();//释放资源
  37. sf.close();//释放资源
  38. }
  39.  
  40. @Test
  41. //session的新增
  42. public void fun2(){
  43. //1 创建,调用空参构造
  44. Configuration conf = new Configuration().configure();
  45. //2 根据配置信息,创建 SessionFactory对象
  46. SessionFactory sf = conf.buildSessionFactory();
  47. //3 获得session
  48. Session session = sf.openSession();
  49. //4 session获得操作事务的Transaction对象
  50. //获得操作事务的tx对象
  51. //Transaction tx = session.getTransaction();
  52. //开启事务并获得操作事务的tx对象(建议使用)
  53. Transaction tx2 = session.beginTransaction();
  54. //----------------------------------------------
  55. Customer c = new Customer();
  56. c.setCust_name("测试");
  57.  
  58. session.save(c);
  59. //----------------------------------------------
  60. tx2.commit();//提交事务
  61. session.close();//释放资源
  62. sf.close();//释放资源
  63. }
  64. @Test
  65. //session的查询
  66. //查询id为1的customer对象
  67. public void fun3(){
  68. //1 创建,调用空参构造
  69. Configuration conf = new Configuration().configure();
  70. //2 根据配置信息,创建 SessionFactory对象
  71. SessionFactory sf = conf.buildSessionFactory();
  72. //3 获得session
  73. Session session = sf.openSession();
  74. //4 session获得操作事务的Transaction对象
  75. //获得操作事务的tx对象
  76. //Transaction tx = session.getTransaction();
  77. //开启事务并获得操作事务的tx对象(建议使用)
  78. Transaction tx2 = session.beginTransaction();
  79. //----------------------------------------------
  80.  
  81. Customer customer = session.get(Customer.class, 1l);
  82.  
  83. System.out.println(customer);
  84. //----------------------------------------------
  85. tx2.commit();//提交事务
  86. session.close();//释放资源
  87. sf.close();//释放资源
  88. }
  89. @Test
  90. //session的修改
  91. //修改id为1的customer对象的name属性为黑马程序员
  92. public void fun4(){
  93. //1 创建,调用空参构造
  94. Configuration conf = new Configuration().configure();
  95. //2 根据配置信息,创建 SessionFactory对象
  96. SessionFactory sf = conf.buildSessionFactory();
  97. //3 获得session
  98. Session session = sf.openSession();
  99. //4 session获得操作事务的Transaction对象
  100. //获得操作事务的tx对象
  101. //Transaction tx = session.getTransaction();
  102. //开启事务并获得操作事务的tx对象(建议使用)
  103. Transaction tx2 = session.beginTransaction();
  104. //----------------------------------------------
  105. //1 获得要修改的对象
  106. Customer c = session.get(Customer.class, 1l);
  107. //2 修改
  108. c.setCust_name("程序员一枚");
  109. //3 执行update
  110. session.update(c);
  111. //----------------------------------------------
  112. tx2.commit();//提交事务
  113. session.close();//释放资源
  114. sf.close();//释放资源
  115. }
  116. @Test
  117. //session的删除
  118. //删除id为1的customer对象
  119. public void fun5(){
  120. //1 创建,调用空参构造
  121. Configuration conf = new Configuration().configure();
  122. //2 根据配置信息,创建 SessionFactory对象
  123. SessionFactory sf = conf.buildSessionFactory();
  124. //3 获得session
  125. Session session = sf.openSession();
  126. //4 session获得操作事务的Transaction对象
  127. //获得操作事务的tx对象
  128. Transaction tx = session.getTransaction();
  129. tx.begin();
  130. //开启事务并获得操作事务的tx对象(建议使用)
  131. Transaction tx2 = session.beginTransaction();
  132. //----------------------------------------------
  133. //1 获得要修改的对象
  134. Customer c = session.get(Customer.class, 1l);
  135. //2 调用delete删除对象
  136. session.delete(c);
  137. //----------------------------------------------
  138. tx2.commit();//提交事务
  139. session.close();//释放资源
  140. sf.close();//释放资源
  141. }
  142. }

6.抽取公共类

  我们发现上面有大量重复的代码,可以将上面的代码进行抽取。抽取获取session的代码

  1. package cn.qlq.utils;
  2.  
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.hibernate.boot.MetadataSources;
  6. import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  7. import org.hibernate.service.ServiceRegistry;
  8.  
  9. public class HibernateUtils {
  10.  
  11. private static SessionFactory sessionFactory;
  12.  
  13. // 创建一个对象,一个web项目只有一个SessionFactory
  14. static {
  15. // 3.3以及之前的版本构建会话工厂对象
  16. // SessionFactory sessionFactory = new
  17. // Configuration().configure().buildSessionFactory();
  18.  
  19. // 5.0之后获取SessionFactory
  20. // 创建服务注册对象
  21. ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
  22. // 创建会话工厂对象
  23. sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
  24. }
  25.  
  26. // 获得session => 获得全新session
  27. public static Session openSession() {
  28. return sessionFactory.openSession();
  29. }
  30.  
  31. // 获得session => 获得与线程绑定的session
  32. public static Session getCurrentSession() {
  33. return sessionFactory.getCurrentSession();
  34. }
  35.  
  36. /**
  37. * 测试方法
  38. *
  39. * @param args
  40. */
  41. public static void main(String[] args) {
  42. System.out.println(HibernateUtils.openSession());
  43. }
  44.  
  45. }

hibernate介绍及环境搭建的更多相关文章

  1. Hibernate 介绍及其 环境搭建

    介绍 数据持久化概念 数据持久化是将内存中的数据模型转换为存储模型,以及将存储模型转换为内存中的数据模型的统称.例如:文件的存储.数据的读取等都是数据持久化操作.数据模型可以是任何数据结构或对象模型, ...

  2. Hibernate 系列 02 - Hibernate介绍及其环境搭建

    引导目录: Hibernate 系列教程 目录 昨晚喝多了,下午刚清醒,继续搞Hibernate.走起. 觉得还行的话,记得点赞哈,给我这个渣渣点学习的动力.有错误的话也请指出,省的我在错误上走了不归 ...

  3. 最新版ssh hibernate spring struts2环境搭建

    最新版ssh hibernate spring struts2环境搭建 最新版spring Framework下载地址:spring4.0.0RELEASE环境搭建 http://repo.sprin ...

  4. Python介绍及环境搭建

    摘自http://www.cnblogs.com/sanzangTst/p/7278337.html Python零基础学习系列之二--Python介绍及环境搭建   1-1.Python简介: Py ...

  5. Django 01 django基本介绍及环境搭建

    Django 01 django基本介绍及环境搭建 #http服务器 #用来接收用户请求,并将请求转发给web应用框架进行处理 #Web应用框架 #处理完请求后在发送给http服务器,http服务器在 ...

  6. [springboot 开发单体web shop] 1. 前言介绍和环境搭建

    前言介绍和环境搭建 简述 springboot 本身是为了做服务化用的,我们为什么要反其道使用它来开发一份单体web应用呢? 在我们现实的开发工作中,还有大量的业务系统使用的是单体应用,特别是对于中小 ...

  7. App自动化测试-1.App自动化介绍和环境搭建

    App自动化测试-1.App自动化介绍和环境搭建 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-b ...

  8. Maven介绍及环境搭建

    Maven介绍及环境搭建 Maven是基于项目对象模型(POM),可以通过一小段描述信息来管理项目的构建.报告和文档的软件项目管理工具. 下载Maven boot:类加载器框架,Maven使用它加在自 ...

  9. Maven快速入门(一)Maven介绍及环境搭建

    做开发的程序员都知道,在系统开发需要各自各样的框架.工具.其中有一种工具不管你是初级程序员还是高级程序员都必须熟练掌握的,那就是项目管理工具(maven.ant.gradle).接下来就总结Maven ...

随机推荐

  1. c#版flappybird 未完全实现

    这些天开始在深圳找工作,想着把从前有些淡忘的技术再温故下.看到尊敬的<传智播客>有一期公开课,讲的是用c#编写flappybird小游戏,也就自己搜了下游戏资源,也来试试看. 其实用到的技 ...

  2. Final互评------《飞词》---- 拉格朗日2018

    一.基于NABCD评论作品,及改进建议 1.根据(不限于)NABCD评论作品的选题; N(Need,需求):拉格朗日2018团队对需求分析的做法是通过问卷调查的形式,通过问卷调查分析出目前的大学生群体 ...

  3. 每日scrum(6)

    今天是小组正式冲刺的第六天,软件的各种结尾工作,还有一些模块就已经全部实现了: 遇到的问题主要是对于自己能力的担忧,以前总是想,如果自己努力,就会怎样成功,其实并不是那样,小小的距离就是很远的能力差距 ...

  4. FPGA---Basys3(实验内容汇总贴)

    前言 本博文为FPGA---Basys3入门板的实验汇总帖子. 实验指导书 实验源码github地址 实验目录 组合逻辑电路设计 编码器 比较器 全加器 时序逻辑电路设计 D 触发器的实现 同步复位的 ...

  5. wifi

    当自己流量不够用时,总想用点免费的wifi 但大部分的wifi都是需要密码的,所以,搜到一款软件,wifi万能钥匙,它的好处就是可以破解一些密码比较简单的wifi,相反,有利也有弊,因为大部分连接的还 ...

  6. 101空降师506团2营E连全体成员

    吕天一 https://coding.net/u/Richardlv http://www.cnblogs.com/Richardlv/ 李伟亮 https://coding.net/u/201304 ...

  7. 如何向妻子解释OOD

      前言 此文译自CodeProject上<How I explained OOD to my wife>一文,该文章在Top Articles上排名第3,读了之后觉得非常好,就翻译出来, ...

  8. php 中间件

    PHP ::双冒号,意为静态成员的访问形式. 中间件$request 速查表:

  9. WBS功能分解及甘特图

    产品 一级子功能 二级子功能 三级子功能 时间(小时)  食物链教学工具 属性面板 功能按键 选择环境 1       自定义生物 2       生物连线与删除 5       显示食物链 1   ...

  10. TP5 关联模型使用(嵌套关联、动态排序以及隐藏字段)

    在数据库设计中,常常会有如下这种关联模型,分类表中一条分类对应多个商品表中的商品 如果要获得分类表中每条分类 以及 对应的商品的信息,则需要先查询分类表中的数据,然后根据结果遍历查询商品表,最后把数据 ...