zoukankan      html  css  js  c++  java
  • 我的Hibernate学习记录(一)

    之前已经过滤一下hibernate的简单的用法,但是近期有点时间,所以重新看下视频,敲下代码,翻下笔记,写博客与大家分享一下。 

    hibernate简介

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

    来自百度百科

    我对hibernate的看法

    其实对于很多的概念,比如什么jpa orm之类的刚刚开始入门的时候可以说是让我自己头晕,天花乱坠的解释触不及防,当我使用了hibernate之后我也就渐渐的了解orm,刚刚入门我就觉得自己先不要太过于深究了,框架就拿来用就行了。
    用了之后发觉hibernate真的挺好,节省了我们的很多时间,不用程序员自己编写SQL语句,而是通过对象的形式去操作数据库,当然还有就是一些需要配合HQL的地方,个人感觉蛮好的。
    不过以对象的形式去映射表,用对象操作数据库,SQL语言的生成掌握在hibernate的手中也暴露了一些问题,你怎么去控制它生成的SQL等等等

    创建项目、搭建环境

    现在开始搭建我们的开发环境,这里我使用的是maven项目

    项目结构图

    如果没有尝试过maven,可以在博客上搜一下,然后配置一下,你会爱上它的
    这里我在porm.xml中引入了相关的依赖

    <dependencies>
            <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.43</version>
            </dependency>
    
        </dependencies>
    

    通过添加了以上的依赖,jar已经就自动的添加到了项目中了,所以现在剩下的就是编码和配置了

    生成pojo(java对象)并写映射文件

    Customer对象
    别问我这是哪里来的,直接拿来用一下就行了

    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 + "]";
        }
    
    }
    

    customer.hbm.xml是一个关于对象的映射文件,它解释了对象中的一些属性在数据库中的表示方式,文件有一定的命名格式,就是后缀需要使用.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 package="cn.lger.domain">
    	<!--声明对象Customer和表cst_customer是关联的,当然了这不是必须的-->
        <class name="Customer" table="cst_customer">
            <!--
            声明表中的每一个字段对应的对象中的属性
            除了id其他的为非必须的
            -->
            <id name="cust_id" column="cust_id">
                <generator class="increment"/>
            </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_linkman" column="cust_linkman" />
            <property name="cust_phone" column="cust_phone" />
            <property name="cust_mobile" column="cust_mobile" />
        </class>
    </hibernate-mapping>
    

    配置hibernate.cfg.xml

    现在接下来就是配置hibernate的配置文件,这里也是有命名规则的,就是后缀需要用.cfg.xml,并且将hibernate.cfg.xml放置于根目录classpath下(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>
        <!--一个配置文件中仅有的一个sessionFactory-->
        <session-factory>
            <!--连接数据库的基本操作-->
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">root</property>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_base</property>
            <!--
            hibernate.hbm2ddl.auto这个参数配置是在hibernate启动的时候对于表的操作的措施
    
    		create		自动建表.每次框架运行都会创建新的表.以前表将会被覆盖,表数据会丢失.(开发环境中测试使用)
    		create-drop 自动建表.每次框架运行结束都会将所有表删除.(开发环境中测试使用)
    		update      自动生成表.如果已经存在不会再生成.如果表有变动.自动更新表(不会删除任何数据).
    		validate	校验.不自动生成表.每次启动会校验数据库中表是否正确.
            -->
            <property name="hibernate.hbm2ddl.auto">update</property>
    
            <!--下列为非必须配置,只是为了开发方便-->
            <!--hibernate.show_sql为true的时候可以在控制台打印出sql-->
            <property name="hibernate.show_sql">true</property>
            <!--hibernate.format_sql为true可以在打印sql的时候格式化,不然sql就是一行,不利于我们观看-->
            <property name="hibernate.format_sql">true</property>
    
            <!--加入映射文件-->
            <mapping resource="customer.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
    

    运行测试

    接下来我创建了一个测试类,用于测试是否成功运行

    public class TestInsertCustomer {
    
        @Test
        public void test01(){
    
            Configuration configuration = new Configuration();
            //初始化hibernate的配置,这里默认的是配置根目录下的hibernate.cfg.xml
            //如果不想用这个函数,或者说不想将配置文件放于根目录可以使用configure(String resource)或configure(URL url)....
            configuration.configure();
            //从会话工厂中拿取session
            SessionFactory sessionFactory = configuration.buildSessionFactory();
            //打开会话
            Session session = sessionFactory.openSession();
            //开启事务
            Transaction transaction = session.beginTransaction();
            //操作数据库部分
            Customer customer = new Customer();
            customer.setCust_name("张三");
            customer.setCust_mobile("1231222");
            //将customer保存到数据库
            session.save(customer);
    
            transaction.commit();
            session.close();
            sessionFactory.close();
        }
    }
    

    当然了,这里可能会有疑问,就是说我们根本不存在这个cst_customer表,它能将数据放进去吗?答案是可以,这是因为hibernate会根据对象创建表。

    完整代码可以上github下载

  • 相关阅读:
    MySQL中内存分为全局内存和线程内存
    mysql 线程级别的缓冲区
    MySQL Handler变量解析
    HANDLER命令与实现
    MySQL Spatial Extensions 地理信息
    C++中临时对象的学习笔记
    HDC与CDC相互转换
    B树
    基于R-Tree的最近邻查询
    地图发布的几种服务的区别
  • 原文地址:https://www.cnblogs.com/lger/p/7524821.html
Copyright © 2011-2022 走看看