zoukankan      html  css  js  c++  java
  • hibernate基础了解1

    1.hibernate概述

      hibernate框架是帮我们完成数据库操作的,应用于dao层;

    2.对象的持久化

      指把内存中的对象形式的数据,转换为数据库的数据,把它永久的保存下来.

    3.好处

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

    4.ORM:object relation mapping.对象关系映射

      利用描述对象和数据库表之间映射的元数据,自动把java应用程序中的对象,持久化到关系型数据库的表中,通过操作java对象,就可以完成对数据库表的操作.

    5.hibernate运行项目必须的jar包

      

    6.hibernate框架的搭建

      创建数据库:准备表,实体

    public class Customer {
        
        /*
         * 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_linkman` VARCHAR(64) 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;
         */
        private Long cust_id;
        
        private String cust_name;
        private String cust_source;
        private String cust_industry;
        private String cust_level;
        private String cust_linkman;
        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_linkman() {
            return cust_linkman;
        }
        public void setCust_linkman(String cust_linkman) {
            this.cust_linkman = cust_linkman;
        }
        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 + "]";
        }
    }

    对象与表的映射配置文件

    导入约束:hibernate-mapping_3.0dtd

    orm元数据:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping SYSTEM 
         "hibernate-mapping-3.0.dtd">
        <!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
    <hibernate-mapping package="com.learn.domain">
        <!-- 
            class元素: 配置实体与表的对应关系的
                name: 完整类名
                table:数据库表名
         -->
         <class name="Customer" table="cst_customer">
         <!-- id元素:配置主键映射的属性
                    name: 填写主键对应属性名
                    column(可选): 填写表中的主键列名.默认值:列名会默认使用属性名
                    type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
                            每个类型有三种填法: java类型|hibernate类型|数据库类型
                    not-null(可选):配置该属性(列)是否不能为空. 默认值:false
                    length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
             -->
             <id name="cust_id" column="cust_id">
                 <generator class="native"></generator>
             </id>
             <!-- property元素:除id之外的普通属性映射
                    name: 填写属性名
                    column(可选): 填写列名
                    type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
                            每个类型有三种填法: java类型|hibernate类型|数据库类型
                    not-null(可选):配置该属性(列)是否不能为空. 默认值:false
                    length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
             -->
            <property name="cust_name" column="cust_name"></property>
             <property name="cust_source" column="cust_source"></property>
             <property name="cust_industry" column="cust_industry"></property>
             <property name="cust_level" column="cust_level"></property>
             <property name="cust_linkman" column="cust_linkman"></property>
             <property name="cust_phone" column="cust_phone"></property>
             <property name="cust_mobile" column="cust_mobile"></property>
             
             <!-- 一对多关系 -->
             <!-- 集合,一对多关系,在配置文件中配置 -->
            <!-- 
                name属性:集合属性名
                column属性: 外键列名
                class属性: 与我关联的对象完整类名
             -->
             <!-- 
                 级联操作:    cascade
                     save-update: 级联保存更新
                     delete:级联删除
                     all:save-update+delete
                 级联操作: 简化操作.目的就是为了少些两行代码.
              -->
              <!-- inverse属性: 配置关系是否维护. 
                      true: customer不维护关系
                      false(默认值): customer维护关系
                      
                  inverse属性: 性能优化.提高关系维护的性能.
                  原则: 无论怎么放弃,总有一方必须要维护关系.
                  一对多关系中: 一的一方放弃.也只能一的一方放弃.多的一方不能放弃.
              -->
             <!-- <set name="linkMans" inverse="true" cascade="save-update">
                 <key column="lkm_cust_id"></key>
                 <one-to-many class="LinkMan" />
             </set> -->
         </class>
    </hibernate-mapping>

    书写主配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration SYSTEM
        "hibernate-configuration-3.0.dtd">
        <hibernate-configuration>
            <session-factory>
                <!-- 
            #hibernate.dialect org.hibernate.dialect.MySQLDialect
            #hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
            #hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
            #hibernate.connection.driver_class com.mysql.jdbc.Driver
            #hibernate.connection.url jdbc:mysql:///test
            #hibernate.connection.username gavin
            #hibernate.connection.password
             -->
                 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
                 <property name="hibernate.connection.url">jdbc:mysql:///hibernate_01</property>
                 <property name="hibernate.connection.username">root</property>
                 <property name="hibernate.connection.password">root</property>
                 <!-- 方言 -->
                 <property name="hibernate.dialect">org.hibernate.dialect.MySQLMyISAMDialect</property>
                 <!-- 线程绑定 -->
                 <property name="current_session_context_class">thread</property>
                 
                 <!-- 将hibernate生成的sql语句打印到控制台 -->
                 <property name="hibernate.show_sql">true</property>
                 <!-- 将hibernate生成的sql语句格式化(语法缩进) -->
                <property name="hibernate.format_sql">true</property>
                <!-- 
                ## auto schema export  自动导出表结构. 自动建表
                #hibernate.hbm2ddl.auto create        自动建表.每次框架运行都会创建新的表.以前表将会被覆盖,表数据会丢失.(开发环境中测试使用)
                #hibernate.hbm2ddl.auto create-drop 自动建表.每次框架运行结束都会将所有表删除.(开发环境中测试使用)
                #hibernate.hbm2ddl.auto update(推荐使用) 自动生成表.如果已经存在不会再生成.如果表有变动.自动更新表(不会删除任何数据).
                #hibernate.hbm2ddl.auto validate    校验.不自动生成表.每次启动会校验数据库中表是否正确.校验失败.
                 -->
                <property name="hibernate.hbm2ddl.auto">update</property>
                <!-- 引入orm元数据
                路径书写: 填写src下的路径
                 -->
                <mapping resource="com/learn/domain/Customer.hbm.xml" />
            </session-factory>
        </hibernate-configuration>

    书写代码测试:

    public class Demo1 {
        @Test
        public void test() {
            //创建加载类对象
            Configuration con  = new Configuration().configure();
            //创建session工厂
            SessionFactory sessionFactory = con.buildSessionFactory();
            //开启session对象
            Session session = sessionFactory.openSession();
            //开启并获得事物操作对象
            Transaction tx = session.beginTransaction();
            
            
            Customer c = new Customer();
            c.setCust_name("111");
            
            
            
            
            session.save(c);
            
            tx.commit();
            session.close();
            sessionFactory.close();
        }
    }

    7.configuration配置对象

      主要用于hibernate框架加载映射文件

    在使用hibernate时,首先要创建configuration实例,configuration实例主要用于启动,加载,管理hibernate的配置文件信息,
    在启动hibernate的过程中,configuration实例首先确定hibernate配置文件的位置,然后读取相关配置,最后创建一个唯一的
    sessionFactory实例.configuration对象只存在于系统的初始化阶段,它将sessionfactory创建完成后,就完成了自己的使命.

    8.sessionfactory:session工厂对象

      sessionfactory接口负责hibernate的初始化和建立session对象,它在hibernate中起到一个缓冲区的作用,
    hibernate可以将自动生成的SQL语句,映射数据以及某些可以重复利用的数据放在这个缓冲区中,同时它还保存了对象数据库配置的所有映射
    关系

    9.session

      session是应用程序与数据库之间交互操作的一个单线程对象,是hibernate运作的中心,是hibernate运作的中心,它的主要功能是为持久化对象提供创建,读取和删除的功能,所有持久化对象必须在session的管理下才可以进行持久化操作

    创建sessionFactory实例后,就可以通过它获取session实例.获取session实例有两种方式,一种是通过openSession()方法,另一种是通过
    getCurrentSession()方法
    以上两种获取session实例方式的主要区别是,采用openSession 方法 获取Session实例时,SessionFactory直接创建一个新的Session实例,
    并且在使用完成后需要调用close方法进行手动关闭.而getCurrentSession方法创建的session实例会被绑定到当前线程中,它在提交或回滚操作时
    会自动关闭
    save(),update(),saveOrUpdate()方法:用于增加和修改对象
    delete()方法:用于删除对象
    get()和load()方法:根据主键查询
    creatQuery()和createSQLQuery()方法:用于数据库操作对象
    createCriteria()方法:条件查询

    10.transaction

      transaction接口主要 用于管理事务,它是hibernate的数据库事务接口.
      transaction接口的事务对象是通过session对象开启的

    commit()方法:提交相关联的session实例

    rollback()方法:撤销事务操作

      session执行完数据操作后,要使用transaction接口的commit方法进行事务提交,才能真正的将数据操作同步到数据库中,
    发生异常时,需要使用rollback方法进行事务回滚,一避免数据发生错误.

  • 相关阅读:
    误加all_load引起的程序报错
    ConstraintLayout 约束布局
    前端判断是否APP客户端打开触屏,实现跳转APP原生组件交互之遐想
    TP5 多条件whereOr查询
    json手动解析详解
    Centos python 2.6 升级到 2.7
    js中click重复执行
    使用 Python 实现实用小工具
    使用 Python 编写密码爆破工具
    使用Python进行无线网络攻击
  • 原文地址:https://www.cnblogs.com/learnjfm/p/7009378.html
Copyright © 2011-2022 走看看