zoukankan      html  css  js  c++  java
  • hibernate之入门

    1.什么是hibernate?

    Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。 Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用。

    2、什么是orm?

    对象关系映射(英语:Object Relation Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。

    对象-关系映射,是随着面向对象的软件开发方法发展而产生的。面向对象的开发方法是当今企业级应用开发环境中的主流开发方法,关系数据库是企业级应用环境中永久存放数据的主流数据存储系统。对象和关系数据是业务实体的两种表现形式,业务实体在内存中表现为对象,在数据库中表现为关系数据。内存中的对象之间存在关联和继承关系,而在数据库中,关系数据无法直接表达多对多关联和继承关系。因此,对象-关系映射(ORM)系统一般以中间件的形式存在,主要实现程序对象到关系数据库数据的映射。

    ORM模型的简单性简化了数据库查询过程。使用ORM查询工具,用户可以访问期望数据,而不必理解数据库的底层结构。

    3.hibernate使用入门

    1、导入相关jar包

    2、编写配置文件

    3、编写测试类,测试功能

    1)导入数据库相关jar包,这里使用的是mysql

     2)日志相关jar包,使用log4j作为日志记录

     3)编写hibernate.cfg.xml,这是hibernate核心配置文件

     
    <?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>
            <!-- 配置关于数据库连接的四个项 driverClass url username password -->
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.url">jdbc:mysql:///test</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">root</property>
    
            <!-- 可以将向数据库发送的sql显示出来 -->
            <property name="hibernate.show_sql">true</property>
            <!-- 格式化sql -->
            <property name="hibernate.format_sql">true</property>
            <!-- hibernate的方言 -->
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <!-- 自动创建表 -->
            <property name="hibernate.hbm2ddl.auto">update</property>
            <!-- 用于设置事务提交方式 -->
            <property name="hibernate.connection.autocommit">false</property>
            <!-- 配置hibernate的映射文件所在位置 -->
            <mapping resource="com/fqh/entity/User.hbm.xml" />
        </session-factory>
    
    </hibernate-configuration>    

    4)编写一个实体类,用于与数据库表映射

    package com.fqh.entity;
    
    public class User {
    
        private int id;
        private String username;
        private String password;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        
    }

    5)编写映射文件User.hbm.xml用于将user表与实体类相映射

    <?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>
        <!--    name属性:         配置将要和数据库映射的类 -->
        <!--    table属性:         配置映射数据库中的哪一个表 -->
        <!--    catalog属性:     配置要操作的数据库 -->
        <class name="com.fqh.entity.User" table="t_user" catalog="test"> 
            <!-- id:        这个标签配置的是主键标签 -->
            <!-- name属性:    指代对应Java对象中的哪个变量 -->
            <!-- column属性:    指代对应数据库中的列名 -->
            <id name="id" column="id">
                <!-- 这里配置的是主键生成策略 -->
                <generator class="native"></generator>
            </id>
            <!-- 这里配置的是除主键外的其他属性以及其和数据库中列的对应关系 -->
            <property name="username" column="username"></property>
            <property name="password" column="password"></property>
        </class>
    
    </hibernate-mapping> 

    6)创建测试类

    package com.fqh.test;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.junit.Test;
    
    import com.fqh.entity.User;
    
    public class HibernateTest {
    
        @Test
        public void test1(){
            //加载配置文件
            Configuration configure = new Configuration().configure();
            //创建session会话工厂
            SessionFactory sessionFactory = configure.buildSessionFactory();
            //通过工厂获取一个session
            Session openSession = sessionFactory.openSession();
            //操作数据库
            //开启事务
            openSession.beginTransaction();
            User user=new User();
            user.setUsername("tom");
            user.setPassword("123");
            openSession.save(user);
            //事务提交
            openSession.getTransaction().commit();
         
    //关闭资源
         openSession。close();
         sessionFactioty.close();
        }
    }

    7)运行结果

     4.hibernate配置以及连接池概念

    1)hibernate工作原理

    1、通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件

    2、由hibernate.cfg.xml中的<mapping resource="xx/xx/xxx.hbm.xml"/>读取解析映射信息。

    3、通过config.buildSessionFactory();//得到sessionFactory

    4sessionFactory.openSession();//得到session

    5session.beginTransaction();//开启事务。

    6session.getTransaction().commit();//提交事务

    7、关闭session;

    8、关闭sessionFactory;

     2)hibernate配置详解

    1.hibernate.cfg.xml配置文件

    可以将hibernate执行的SQL语句打印出来

    <property name="hibernate.show_sql">true</property>

    格式化SQL语句

    <property name="hibernate.format_sql">true</property>

    指定数据库MySQL,用到hibernate特定方言

    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

    自动创建表,

    <property name="hibernate.hbm2ddl.auto">update</property>

    可选属性:

    Create-drop 每次都会创建一个新的表,执行完成后删除。一般在测试中使用

    Create   每次都会创建一个新的表,一般是在测试中使用

    update 如果数据库中有表,不创建,没有表创建,如果映射不匹配,会自动更新表结构(只能添加)

    validate  只会使用存在的表,并且会对映射关系进行校验.

    事务的提交方式

    <property name="hibernate.connection.autocommit">false</property>

    2.映射文件

    主键生成策略

    <generator class="native"></generator>

    配置非主键属性

    <property name="username" column="username"></property>

    关于hibernate的映射文件中类型问题

    对于type属性它的取值,可以有三种:

    1. java中的数据类型
    2. hibernate中的数据类型
    3. SQL的数据类型

     默认是hibernate中数据类型,type可写可不写

    3)hibernate常用api介绍

    1.configuration

    它主要是用于加载hibernate配置.

    Configuration config=new Configuration().config(); 主要加载src下的hibernate.cfg.xml

    Configuration config=new Configuration();主要加载的src下的hibernate.properties

    Configuration config=new Configuration().config(核心配置文件名称);加载指定的名称的配置文件

     2.sessionFactory

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

    4)在hibernate中引入c3p0

    1. 我们要导入c3p0的相关jar包(一共是三个)
    2. hibernate.cfg.xml文件中配置c3p0连接
    <!-- 设置连接提供者 -->
    <property name="hibernate.connection.provider_class">
    org.hibernate.connection.C3P0ConnectionProvider
    </property>
    <!-- c3p0连接池的配置 -->
    <property name="hibernate.c3p0.max_size">20</property> <!-- 最大连接池 -->
    <property name="hibernate.c3p0.min_size">5</property> <!-- 最小连接数 -->
    <property name="hibernate.c3p0.timeout">120</property> <!-- 超时 -->
    <property name="hibernate.c3p0.idle_test_period">3000</property> <!-- 空闲连接 -->

    5.hibernate实现增删改查

    1)修改

        //修改
        @Test
        public void test2() {
            Configuration configure = new Configuration().configure();
            //创建session会话工厂
            sessionFactory = configure.buildSessionFactory();
            //通过工厂获取一个session
            Session openSession = sessionFactory.openSession();
            //操作数据库
            //开启事务
            openSession.beginTransaction();
            User user=new User();
            user.setId(1);
            user.setUsername("admin");
            user.setPassword("admin");
            openSession.update(user);
            openSession.getTransaction().commit();
            openSession.close();
            sessionFactory.close();
        }

    2)删除

        //删除
        @Test
        public void test3() {
            Configuration configure = new Configuration().configure();
            //创建session会话工厂
            sessionFactory = configure.buildSessionFactory();
            //通过工厂获取一个session
            Session openSession = sessionFactory.openSession();
            //操作数据库
            //开启事务
            openSession.beginTransaction();
            User user=new User();
            user.setId(1);
            openSession.delete(user);
            openSession.getTransaction().commit();
            openSession.close();
            sessionFactory.close();
        }

    3)根据id查询(get/load,load是懒加载)

            //根据id查询
            @Test
            public void test4() {
                Configuration configure = new Configuration().configure();
                //创建session会话工厂
                sessionFactory = configure.buildSessionFactory();
                //通过工厂获取一个session
                Session openSession = sessionFactory.openSession();
                //操作数据库
                User user = openSession.get(User.class, 2);//需要返回的类型,传入的id
                System.out.println(user.getUsername()+user.getPassword());
                openSession.close();
                sessionFactory.close();
            }

    一点点学习,一丝丝进步。不懈怠,才不会被时代所淘汰!

  • 相关阅读:
    mysql数据库安装与配置
    redis主从配置+sentinel哨兵模式
    Oracle 本地验证和密码文件
    Oracle 12c hub和leaf的转换
    oracle 12c CPU资源隔离
    oracle12 listagg 与 wm_concat行列转换
    Oracle 12c rac搭建
    ClassLoader.loadClass()与Class.forName()的区别《 转》
    docker 安装mysql8.0
    spring boot @EnableWebMvc禁用springMvc自动配置原理。
  • 原文地址:https://www.cnblogs.com/fqh2020/p/12000271.html
Copyright © 2011-2022 走看看