hibernate入門

學習hibernate的一個Demo,使用hibernate對Customer類進行單表增刪改查,hibernate是ORM對象關係映射技術,能夠對JDBC數據庫底層操做進行封裝,簡化開發。java

1.環境搭建

官網上下載hibernate的依賴包,hibernate能夠再java環境下也能夠在web環境下進行開發,咱們使用java環境。mysql

2.進行項目配置

   2.1建一個customer表,什麼表均可以,這裏建一個customer表作演示,表中添加一些屬性。web

   2.2根據customer表新建java類。sql

   2.3根據java類,新建對象映射文件,xxx.hbm.xml,配置二者映射關係。數據庫

   2.4配置核心文件,文件主要配置鏈接數據庫信息和映射表。apache

   2.5.編寫測試類,進行測試緩存

3.代碼展現

package hibernate;
/**
 * 客戶管理的實體類
 * @author jt
 *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;
 */
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 + "]";
    }
    
}
<?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="hibernate">
       <class name="Customer" table="cst_customer">
            <id name="cust_id" column="cust_id">
                 <generator class="native"/>
            </id>
            <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_phone" column="cust_phone"></property>
            <property name="cust_mobile" column="cust_mobile"></property>
       </class>
    </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/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://127.0.0.1/hibernate_day01</property>
          <property name="hibernate.connection.username">root</property>
          <property name="hibernate.connection.password">root</property>
          <property name="hibernate.show_sql">true</property>
          <property name="hibernate.format_sql">true</property>
          <!-- 自動建表 -->
          <property name="hibernate.hbm2ddl.auto">update</property>
          <!-- 配置方言 -->
          <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
          <!-- 配置映射 -->
          <mapping resource="hibernate/customer.hbm.xml"></mapping>
      </session-factory>
    </hibernate-configuration>
package hibernate;



import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class hibernateDemo1 {
     public static void main(String[] args) {
          //1.加載核心配置文件
         Configuration configuration = new Configuration().configure();
         //2.建立sessionFactory對象
         SessionFactory sessionFactory = configuration.buildSessionFactory();
         //3.經過sesstionFactory獲取session對象
         Session session = sessionFactory.openSession();
         //4.手動開啓事務
         Transaction transaction = session.beginTransaction();
         //5.編寫測試代碼
         Customer customer = new Customer();
         customer.setCust_name("h");
         session.save(customer);
         //6.事務提交
         transaction.commit();
         //7.資源釋放
         session.close();
         System.out.println("成功了");
    }
    
}

4.主要對象

    4.1Configuation對象,加載配置文件安全

    4.2SessionFactory對象,封裝了一個數據庫鏈接池,二級緩存,線程安全。session

    4.3Session對象,數據庫操做對象,對數據庫進行增刪改查操做,線程不安全。app

    4.4Transaction對象,數據庫事務操做對象。

5.數據庫操做方法

   5.1插入操做save

   5.2查找操做get(Object.class,id)和load,get當即操做,load延遲操做,get返回具體對象。

   5.3刪除操做delete。

   5.4批量查詢Query,能夠使用hql和sql兩種方式,creatQuery和creatSQLQuery。

   5.5saveOrUpdate

 6.注意事項

實體類對象的hbm.xml文件的class的類名name可能會包解析文件錯誤,類名須要在mapping中設置包名,不要在class中的name中帶上包名。

hibernate.cfg.xml中的mapping配置的映射名resource用/分開。

7.優化處理

能夠封裝一個工具類簡化開發。

package hibernate;



import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class hibernateUtils {
        public static final Configuration cfg;
        public static final SessionFactory sf;
        
        static {
            cfg=new Configuration().configure();
            sf=cfg.buildSessionFactory();
        }
        public static Session openSession() {
            return sf.openSession();
        }
}

能夠添加log4j.properties文件打印log信息

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###
# error warn info debug trace
log4j.rootLogger= info, stdout
相關文章
相關標籤/搜索