Hibernate V5

    xiaoxiao2026-04-22  7

    Hibernate V5.0框架入门-映射文件配置

    一.概述

    1.CRM的概述

    什么是CRM?

    CRM(Customer Relationship Management) 客户关系管理,是利用相应的信息技术以及互联网技术来协调企业与顾客在销售,营销和服务上的交互,向客户提供新式的个性化的客户交互和服务的过程。其最终目标是将面向客户的各项信息和活动集成起来,组件一个一客户为中心的企业,实现面向客户的活动的全面管理。

    2.CRM有哪些模块?

    CRM系统中客户信息管理模块功能包括:

    客户信息管理,联系人管理,客户拜访管理,综合查询,统计分析,系统管理

    3.Hibernate框架概述

    框架:软件的半成品,已经完成了部分功能

    EE的三层架构

    Web层:Servlet,JSP,Struts2,SpringMVC

    业务逻辑层:JavaBean,Spring

    持久层:JDBC,Hibernate,MyBatis,DbUtils,JdbcTemplate

    Servlet+JSP+JavaBean+JDBC使用这套框架开发市面上所有应用,但是在企业中不会使用(过于底层),企业中开发一般使用SSH(Struts+Spring+Hibernate),SSM(SpringMVC+Spring+Mybatis)。

    什么是Hibernate?

    Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。Hibernate的核心接口一共有6个,分别为:Session、SessionFactory、Transaction、Query、Criteria和Configuration。

    Hibernate将POJO与数据库表建立映射关系,是一个全自动的orm框架,Hibernate可以自动生成SQL语句自动执行。

    什么是ORM?

    对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。那么,到底如何实现持久化呢?一种简单的方案是采用硬编码方式,为每一种可能的数据库访问操作提供单独的方法。

    二.Hibernate环境搭建

    1.下载Hibernate5

    https://hibernate.org/

    2.创建项目,导入相应jar包。

    数据库驱动包:mysql-connector-java-5.1.7-bin.jarhibernate开发的必须包:required目录日志记录包

    3.创建数据库表

    CREATE TABLE `cst_customer` ( `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)', `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)', `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源', `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业', `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别', `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话', `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话', PRIMARY KEY (`cust_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

    4.创建实体类

    package com.nike.hibernate5.pojo; /** * 这是客户管理的实体类 * @author 猪猪 * */ public class Customer { private Long cust_id; private String cust_name; private String cust_source; private String cust_industry; private String cust_level; private String cust_phone; private String cust_mobile; public Long getCust_id() { return cust_id; } public void setCust_id(Long cust_id) { this.cust_id = cust_id; } public String getCust_name() { return cust_name; } public void setCust_name(String cust_name) { this.cust_name = cust_name; } public String getCust_source() { return cust_source; } public void setCust_source(String cust_source) { this.cust_source = cust_source; } public String getCust_industry() { return cust_industry; } public void setCust_industry(String cust_industry) { this.cust_industry = cust_industry; } public String getCust_level() { return cust_level; } public void setCust_level(String cust_level) { this.cust_level = cust_level; } public String getCust_phone() { return cust_phone; } public void setCust_phone(String cust_phone) { this.cust_phone = cust_phone; } public String getCust_mobile() { return cust_mobile; } public void setCust_mobile(String cust_mobile) { this.cust_mobile = cust_mobile; } @Override public String toString() { return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + ", cust_source=" + cust_source + ", cust_industry=" + cust_industry + ", cust_level=" + cust_level + ", cust_phone=" + cust_phone + ", cust_mobile=" + cust_mobile + "]"; } }

    5.创建映射关系(xml配置文件,任意命名,类名.hbm.xml)

    Customer.hbm.xml

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- 建立类与表的映射 --> <class name="com.nike.hibernate5.pojo.Customer" table="cst_customer"> <!-- 建立类中属性与表中主键对应 --> <id name="cust_id" column="cust_id"> <!-- 主键生成策略 :native本地策略--> <generator class="native"/> </id> <!-- 建立类中普通属性和表字段的对应 --> <property name="cust_name" column="cust_name"/> <property name="cust_source" column="cust_source"/> <property name="cust_industry" column="cust_industry"/> <property name="cust_level" column="cust_level"/> <property name="cust_phone" column="cust_phone"/> <property name="cust_mobile" column="cust_mobile"/> </class> </hibernate-mapping>

    6.创建一个Hibernate核心配置文件

    Hibernate核心配置文件名称:hibernate.cfg.xml,在src下创建

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置数据库基本参数信息 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate5_demo1</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">971102</property> <!-- 配置Hibernate的方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 可选配置 --> <!-- 打印SQL语句 --> <property name="hibernate.show_sql">true</property> <!-- 格式化SQL语句 --> <property name="hibernate.format_sql">true</property> <!-- 引入映射文件 --> <mapping resource="co/nike/hibernate5/pojo/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>

    7.编写测试类

    package com.nike.hibernate5.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Test; import com.nike.hibernate5.pojo.Customer; /** * Hibernate入门测试类 * @author 猪猪 */ public class HibernateTest01 { //保存客户 @Test public void test01(){ //1.加载Hibernate核心配置文件; Configuration configuration = new Configuration().configure(); //2.创建一个SessionFactory对象:类似于JDBC连接池 SessionFactory sessionFactory = configuration.buildSessionFactory(); //3.通过SessionFactory获取Session对象:类似于JDBC中的Connection Session session = sessionFactory.openSession(); //4.手动开启事务:为兼容Hibernate3 Transaction transaction = session.beginTransaction(); //5.操作数据库中的表 Customer customer = new Customer(); customer.setCust_name("李元霸"); customer.setCust_industry("大唐征伐有限集团"); session.save(customer); //6.事务提交 transaction.commit(); //7.释放资源 session.close(); } }

    三.Hibernate的常见配置

    1.XML的提示的配置

    windosws—>perference—>xml CataLog—>add

    2.映射的配置

    Hibernate可以根据映射文件帮我们在数据库中创建表。

    <class>标签的配置 用来建立类与表的映射关系,常用属性name:类的全路径table:数据库中对应的表名,类名和表名一致,table属性可以省略catalog:数据库名,可以不写 <id>标签的配置 用来建立类中属性与表中主键的对应关系常用属性name:类中的属性名column:表中的字段名,属性名与字段名一致,column属性可以省略length:长度type:类型 <property>标签的配置 用来建立类中的普通属性与表中字段的对应关系name:类中属性名column:表中字段名,属性名与字段名一致,column属性可以省略length:长度type:类型(Java类型,Hibernate中的类型,数据库的类型)not-null:非空约束unique:唯一约束

    3.核心配置

    必需配置 连接数据库的基本参数 驱动类URL用户名密码 方言 可选配置 打印SQL语句:hibernate.show_sql格式化SQL语句:hibernate.format_sql自动创建表:hibernate.hbm2ddl.auto,值有: None:不用Hibernate自动创建表create:如果数据库中有该表,那么删除该表,有hibernate创建表,如果没有表,那就新建表,每一次都会创建表。(测试)create-drop:若数据库有该表,那么删除原有表,有hibernate创建表,操作执行完后,会再次删除创建的表。如果没有表,那就新建表,操作执行完后,会再次删除创建的表。(测试)操作执行完,指关闭SessionFactory。update:如果数据库中有表,就使用数据库中的表,如果没有表就会创建新的表(可以更新表结构)。validate:校验,如果没有表,不会创建表,只会数据库原有的表,会校验映射和表结构是否一致,不一致就会报错。 引入映射文件配置 <mapping resource=“com/nike/hibernate5/pojo/Customer.hbm.xml”/>

    Hibernate的核心配置有两种方式:

    1.属性文件:hibernate.properties,属性文件的方式不能引入映射文件(手动编写代码加载映射文件)

    2.XML文件:hibernate.cfg.xml

    4.Hibernate的核心API

    (1)Configuration:Hibernate的配置对象

    用来加载核心配置文件,加载映射文件

    hibernate.properties

    Configuration config = new Configuration(); //已经加载了hibernate.properties配置文件 //手动加载映射文件 config.addResource("Customer.xml的全路径")

    hibernate.cfg.xml

    Configuration config = new Configuration().configure(); //手动加载映射文件 config.addResource("Customer.xml的全路径")

    (2)SessionFactory:Session工厂

    SessionFactory接口负责初始化Hibernate。它充当数据存储源(连接池)的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。

    SessionFactory内部维护了Hibernate的连接池和二级缓存。是线程安全的对象,一个项目只需创建一个SessionFactory即可。

    核心配置中配置C3P0连接池

    <!-- 配置C3P0连接池 --> <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <!--在连接池中可用的数据库连接的最少数目 --> <property name="c3p0.min_size">5</property> <!--在连接池中所有数据库连接的最大数目 --> <property name="c3p0.max_size">20</property> <!--设定数据库连接的过期时间,以秒为单位, 如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 --> <property name="c3p0.timeout">120</property> <!--每3000秒检查所有连接池中的空闲连接 以秒为单位--> <property name="c3p0.idle_test_period">3000</property>

    抽取创建SessionFactory的工具类

    package com.nike.hibernate5.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Hibernate工具类 * @author 猪猪 * */ public class HibernateUtils { private static Configuration configuration; private static SessionFactory factory; static{ configuration = new Configuration().configure(); factory = configuration.buildSessionFactory(); } public static Session openSession(){ return factory.openSession(); } }

    (3)Session:类似JDBC中的Connection对象,连接对象

    Session接口负责执行被持久化对象的CRUD操作(CRUD的任务是完成与数据库的交流,包含了很多常见的SQL语句)。但需要注意的是Session对象是非线程安全的。同时,Hibernate的session不同于JSP应用中的HttpSession。这里当使用session这个术语时,其实指的是Hibernate中的session,而以后会将HttpSession对象称为用户session。

    Session中常用的API:

    Serializable save(Object obj):插入数据,返回id

    T get(Class class,Serializable id):查询数据

    //get查询数据 @Test public void test03(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); Customer customer = session.get(Customer.class, 1l); transaction.commit(); System.out.println(customer); session.close(); }

    T load(Class class,Serializable id):查询数据

    //load查询数据 @Test public void test04(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); Customer customer = session.load(Customer.class, 2l); transaction.commit(); System.out.println(customer); session.close(); }

    get与load的区别:

    get方法采用的是立即加载,即执行到get方法就发送sql语句,并返回查询结果,查询结果返回真实对象本身。当数据库不存在该条数据时,返回null。load方法采用的是延迟加载(懒加载),执行到load方法是不会发送sql语句,也不会返回结果,只有在使用到查询结果的未知属性(除id意外)时才会发送SQL语句,返回查询结果。返回不是真实对象,而是一个代理对象。利用assist产生动态代理。当数据库不存在该条数据时,会抛出ObjectNotFoundExecption。

    void update(Object obj):修改记录

    //update修改数据 @Test public void test05(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); //直接创建对象进行修改 Customer customer = new Customer(); customer.setCust_id(1l); customer.setCust_name("李世明"); customer.setCust_industry("大唐征伐有限集团"); customer.setCust_level("10"); customer.setCust_mobile("94174110"); customer.setCust_phone("94174120"); customer.setCust_source("web"); session.update(customer); transaction.commit(); session.close(); } //update修改数据 @Test public void test05(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); //先查询在修改 Customer customer = session.get(Customer.class, 2l); customer.setCust_level("5"); customer.setCust_mobile("5201314"); customer.setCust_phone("5201314"); customer.setCust_source("tel"); session.update(customer); transaction.commit(); session.close(); }

    void delete(Object obj):删除记录

    //delete删除数据 @Test public void test06(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); //直接创建对象进行修改 Customer customer = session.get(Customer.class, 3l); System.out.println(customer); session.delete(customer); transaction.commit(); session.close(); }

    void saveOrUpdate(Object obj):保存或更新数据,设置了主键就是更新操作,若数据库中不存在该主键就报错。

    查询所有记录

    //查询所有数据 @Test public void test07(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); //接收HQL:Hibernate Query Language 面向对象的查询语句 Query query = session.createQuery("from Customer"); List<Customer> list = query.list(); for (Customer customer : list) { System.out.println(customer); } transaction.commit(); session.close(); } //查询所有数据 @Test public void test08(){ Session session = HibernateUtils.openSession(); Transaction transaction = session.beginTransaction(); //接收SQL Query query = session.createSQLQuery("select * from cst_customer"); List<Object[]> list = query.list(); for (Object[] objects : list) { System.out.println(Arrays.toString(objects)); } transaction.commit(); session.close(); }

    (4)Transaction:事务对象

    Transaction 接口是一个可选的API,可以选择不使用这个接口,取而代之的是Hibernate 的设计者自己写的底层事务处理代码。 Transaction 接口是对实际事务实现的一个抽象,这些实现包括JDBC的事务、JTA 中的UserTransaction、甚至可以是CORBA 事务。之所以这样设计是能让开发者能够使用一个统一事务的操作界面,使得自己的项目可以在不同的环境和容器之间方便地移植。

    commit():提交事务rollback():事务回滚
    最新回复(0)