Hibernate_01

Hibernate

hibernate是一个持久层orm框架,目的:简化项目开发,提高开发效率。

快速入门

  • 下载hibernate,然后导入hibernate->lib->required下面的所有jar包,还有就是数据库驱动的jar包。
  • 创建表cst_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_address` varchar(128) DEFAULT NULL COMMENT '客户联系地址',
    `cust_phone` varchar(64) DEFAULT NULL COMMENT '客户联系电话',
    PRIMARY KEY (`cust_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
    
  • 创建相应的实体类 Customer.java

      public class Customer implements Serializable {
      private static final long serialVersionUID = 1L;
      private Long id;// 主键
      private String custName;// 客户姓名
      private String custSource; // 客户来源
      private String custIndustry; // 所属行业
      private String custLevel; // 客户级别
      private String custAddress; // 地址
      private String custPhone; // 电话
    
      public Long getId() {
          return id;
      }
      public void setId(Long id) {
          this.id = id;
      }
      public String getCustName() {
          return custName;
      }
      public void setCustName(String custName) {
          this.custName = custName;
      }
      public String getCustSource() {
          return custSource;
      }
      public void setCustSource(String custSource) {
          this.custSource = custSource;
      }
      public String getCustIndustry() {
          return custIndustry;
      }
      public void setCustIndustry(String custIndustry) {
          this.custIndustry = custIndustry;
      }
      public String getCustLevel() {
          return custLevel;
      }
      public void setCustLevel(String custLevel) {
          this.custLevel = custLevel;
      }
      public String getCustAddress() {
          return custAddress;
      }
      public void setCustAddress(String custAddress) {
          this.custAddress = custAddress;
      }
      public String getCustPhone() {
          return custPhone;
      }
      public void setCustPhone(String custPhone) {
          this.custPhone = custPhone;
      }
      @Override
      public String toString() {
          return "Customer [id=" + id + ", custName=" + custName + ", custSource=" + custSource + ", custIndustry="
                  + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress + ", custPhone="
                  + custPhone + "]";
      }
    }
    
  • 创建对应的配置文件 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 : 实体类的全限定名
          table : 对应数据库的表名(如果类名和数据库表的名字一样,可以省略table配置)
       -->
      <class name="com.xiaoshitou.domain.Customer" table="cst_customer">
          <!-- id标签:主键
              name : 实体类中的id
              column : 数据库中主键的名字
           -->
          <id name="id" column="cust_id">
              <!-- gennerator class:主键的生成策略;native表示,主键由数据库自动维护 -->
              <generator class="native"></generator>
          </id>
    
          <!-- property:主键以外的普通字段
           name=>实体类中的成员变量,column=>表中的字段名  -->
          <property name="custName" column="cust_name"></property>
          <property name="custSource" column="cust_source"></property>
          <property name="custIndustry" column="cust_industry"></property>
          <property name="custLevel" column="cust_level"></property>
          <property name="custAddress" column="cust_address"></property>
          <property name="custPhone" column="cust_phone"></property>
      </class>
    </hibernate-mapping>
    
  • 编写hiberna核心配置文件:一定要放在src目录下,hibernate.cfg.xml

    <?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/hibernate</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password">123456</property>
          <!-- 配置数据库方言 -->
          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    
          <!-- 显示sql -->
          <property name="hibernate.show_sql">true</property>
          <!-- 格式化sql -->
          <property name="hibernate.format">true</property>
          <!-- create-drop:启动时会创建表,sessionFactory关闭时删除表,
              create: 每次都会重新创建表,
              update: 如果实体类和数据库的表字段不一样时,会修改数据库中的字段,保证实体类和数据库表是同步的,
              validate: 如果实体类和数据库表字段不一致时,会报错  -->
          <property name="hibernate.hbm2ddl.auto">update</property>
    
          <!-- 把实体类的配置文件加载到核心配置文件中 -->
          <mapping resource="com/xiaoshitou/domain/Customer.hbm.xml"/>
    
      </session-factory>
    </hibernate-configuration>
    
  • 编写测试类,使用hibernate来添加一条数据

    /**
       * 快速入门:利用hibernate添加一条数据
       */
      @Test
      public void test01() {
          // 创造一个customer对象
          Customer customer = new Customer();
          customer.setCustName("东方科技");
          customer.setCustLevel("VIP");
          customer.setCustSource("朋友推荐");
          customer.setCustIndustry("无人机");
          customer.setCustAddress("东方1号路");
          customer.setCustPhone("8221365");
    
          // 利用hibernate完成保存
          Configuration configuration = new Configuration();
          configuration.configure();
          // 创建sessionFactory
          SessionFactory sessionFactory = configuration.buildSessionFactory();
          // 获取session
          Session session = sessionFactory.openSession();
          // 开启事务
          Transaction tx = session.beginTransaction();
          // 保存
          session.save(customer);
          // 提交事务,关闭资源
          tx.commit();
          session.close();
          sessionFactory.close();
      }
    

    hibernate 使用c3p0连接池

  • 导入jar包:hibernate-release-5.0.7.Final\lib\optional\c3p0
  • 在hibernate.cfg.xml中添加配置

    <?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>
          <!-- 使用c3p0连接池 -->
          <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
          <!-- 在数据库连接池中,最大连接数 -->
          <property name="hibernate.c3p0.max_size">20</property>
          <!-- 在数据库连接池中,最小连接数 -->
          <property name="hibernate.c3p0.min_size">5</property>
          <!-- 如果连接池中,某个连接空闲时间超过设置的时间,将会被从连接池冲清除 -->
          <property name="hibernate.c3p0.timeout">5000</property>
          <!-- 每个3000秒检查,连接池中的空闲连接,单位秒 -->
          <property name="hibernate.c3p0.idle_test_period">3000</property>
    
          <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
          <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password">123456</property>
          <!-- 配置数据库方言 -->
          <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>
          <!-- create-drop:启动时会创建表,sessionFactory关闭时删除表,
              create: 每次都会重新创建表,
              update: 如果实体类和数据库的表字段不一样时,会修改数据库中的字段,保证实体类和数据库表是同步的,
              validate: 如果实体类和数据库表字段不一致时,会报错  -->
          <property name="hibernate.hbm2ddl.auto">update</property>
    
          <!-- 把实体类的配置文件加载到核心配置文件中 -->
          <mapping resource="com/xiaoshitou/domain/Customer.hbm.xml"/>
    
      </session-factory>
    </hibernate-configuration>
    

    session中的saveOrUpdate方法:

  • 如果对象中没有设置id,就会新增一条记录
  • 如果对象中设置了id,并且数据库中,有对应id的记录,那么就是修改记录
  • 如果对象中设置了id,在数据库中没有对应id的记录,那么将会执行失败,抛出异常。

    session中get和load方法的区别

  • get是立即加载(立即执行sql语句),load是延迟加载(在真正使用对象的属性时,才会发送sql语句)
  • get返回的对象是要查询的实体对象,load返回的代理对象

 

posted @ 2017-08-14 19:58  小石头tester  阅读(163)  评论(0编辑  收藏  举报