如何徹底根據官方下載包搭建hibernate框架

  很久沒有用s2sh的框架了,最近業務須要又要拾起來。在搭框架時,發現以前都是複製配置文件,對具體的細節卻很懵懂,因此要重新來一遍,也是一次新的學習。html

  我使用的版本是hibernate-release-4.3.11.Final,由於須要使用基於xml的配置,這一版本關於xml的文檔仍是很友好的,最新的5.x主要針對註解,與業務有所出入。java

  下面開始搭建:mysql

  百度雲:jar包連接  密碼:h7o8web

關於文件結構

  搭建Hibernate的壓縮文件解壓後就是下面的結構:sql

  

  jdbc和log4j包是我後加的,其餘是就是hibernate的,下面說下他這幾個文件夾的大體用途數據庫

  documentation文件夾:存放了Hibernate的使用文檔和框架API等,下面會用到。session

  lib文件夾:存放的是hibernate所須要的jar包。app

  project文件夾:存放的是一些小項目實例,裏面的etc會用到。框架

關於jar包

  搭建Hibernate,首先就是jar包,而Hibernate的jar包就在lib/required文件夾裏,下面是這些jar包的做用dom

  

  有了這些jar包,Hibernate的功能就全了,可是Hibernate是操做數據庫的,因此咱們還須要提供咱們要使用的數據庫的對應的驅動。如mysql的驅動包。

  在開發過程當中,咱們必然還須要記錄捕捉項目的運行狀況,因此還須要log4j的支持,進官網下載便可

下載完的文件裏有不少jar包,用哪一個呢,官網的下面說的很清楚。

到這裏,jar包就準備完成了,

 建立項目

  建立一個項目。

  1、file-new-javaProject 填寫項目名便可,由於主要說明Hibernate的使用,不須要web,因此直接用JavaProject,若是使用web也是同樣的道理。

  導入jar包

  1、建立一個文件夾,將上面Hibernate的required文件夾的jar包、jdbc的jar包、log4j的jar包都copy進來

  2、全選,鼠標右鍵-buildPath-add to build path

  建立一個數據表

  建立一個數據庫,並添加一個表,下面是一個示例。也能夠本身隨意建立。

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `u_id` int(11) NOT NULL AUTO_INCREMENT,
  `u_email` varchar(60) DEFAULT NULL,
  `u_name` varchar(100) DEFAULT NULL,
  `u_username` varchar(100) DEFAULT NULL,
  `u_password` varchar(70) DEFAULT NULL,
  `u_age` varchar(255) DEFAULT NULL,
  `u_detail` varchar(255) DEFAULT NULL,
  `u_avatar` varchar(255) DEFAULT NULL,
  `is_admin` varchar(5) DEFAULT NULL,
  `createtime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `updatetime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`u_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
View Code

  建立一個表對應的實體類

  先建一個com.xx.domain的包,將實體類放入包中

package com.cky.domain;

import java.sql.Timestamp;

public class User {
    private Integer uId;
    private String uEmail;
    private String uName;
    private String uUsername;
    private String uPassword;
    private String uAge;
    private String uDetail;
    private String uAvatar;
    private String isAdmin;
    private Timestamp createtime;
    private Timestamp updatetime;

    public Integer getuId() {
        return uId;
    }

    public void setuId(Integer uId) {
        this.uId = uId;
    }

    public String getuEmail() {
        return uEmail;
    }

    public void setuEmail(String uEmail) {
        this.uEmail = uEmail;
    }

    public String getuName() {
        return uName;
    }

    public void setuName(String uName) {
        this.uName = uName;
    }

    public String getuUsername() {
        return uUsername;
    }

    public void setuUsername(String uUsername) {
        this.uUsername = uUsername;
    }

    public String getuPassword() {
        return uPassword;
    }

    public void setuPassword(String uPassword) {
        this.uPassword = uPassword;
    }

    public String getuAge() {
        return uAge;
    }

    public void setuAge(String uAge) {
        this.uAge = uAge;
    }

    public String getuDetail() {
        return uDetail;
    }

    public void setuDetail(String uDetail) {
        this.uDetail = uDetail;
    }

    public String getuAvatar() {
        return uAvatar;
    }

    public void setuAvatar(String uAvatar) {
        this.uAvatar = uAvatar;
    }

    public String getIsAdmin() {
        return isAdmin;
    }

    public void setIsAdmin(String isAdmin) {
        this.isAdmin = isAdmin;
    }

    public Timestamp getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Timestamp createtime) {
        this.createtime = createtime;
    }

    public Timestamp getUpdatetime() {
        return updatetime;
    }

    public void setUpdatetime(Timestamp updatetime) {
        this.updatetime = updatetime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (uId != user.uId) return false;
        if (uEmail != null ? !uEmail.equals(user.uEmail) : user.uEmail != null) return false;
        if (uName != null ? !uName.equals(user.uName) : user.uName != null) return false;
        if (uUsername != null ? !uUsername.equals(user.uUsername) : user.uUsername != null) return false;
        if (uPassword != null ? !uPassword.equals(user.uPassword) : user.uPassword != null) return false;
        if (uAge != null ? !uAge.equals(user.uAge) : user.uAge != null) return false;
        if (uDetail != null ? !uDetail.equals(user.uDetail) : user.uDetail != null) return false;
        if (uAvatar != null ? !uAvatar.equals(user.uAvatar) : user.uAvatar != null) return false;
        if (isAdmin != null ? !isAdmin.equals(user.isAdmin) : user.isAdmin != null) return false;
        if (createtime != null ? !createtime.equals(user.createtime) : user.createtime != null) return false;
        if (updatetime != null ? !updatetime.equals(user.updatetime) : user.updatetime != null) return false;

        return true;
    }

    @Override
    public String toString() {
        return "User{" +
                "uId=" + uId +
                ", uEmail='" + uEmail + '\'' +
                ", uName='" + uName + '\'' +
                ", uUsername='" + uUsername + '\'' +
                ", uPassword='" + uPassword + '\'' +
                ", uAge='" + uAge + '\'' +
                ", uDetail='" + uDetail + '\'' +
                ", uAvatar='" + uAvatar + '\'' +
                ", isAdmin='" + isAdmin + '\'' +
                ", createtime=" + createtime +
                ", updatetime=" + updatetime +
                "}\n";
    }

    @Override
    public int hashCode() {
        Integer result = uId;
        result = 31 * result + (uEmail != null ? uEmail.hashCode() : 0);
        result = 31 * result + (uName != null ? uName.hashCode() : 0);
        result = 31 * result + (uUsername != null ? uUsername.hashCode() : 0);
        result = 31 * result + (uPassword != null ? uPassword.hashCode() : 0);
        result = 31 * result + (uAge != null ? uAge.hashCode() : 0);
        result = 31 * result + (uDetail != null ? uDetail.hashCode() : 0);
        result = 31 * result + (uAvatar != null ? uAvatar.hashCode() : 0);
        result = 31 * result + (isAdmin != null ? isAdmin.hashCode() : 0);
        result = 31 * result + (createtime != null ? createtime.hashCode() : 0);
        result = 31 * result + (updatetime != null ? updatetime.hashCode() : 0);
        return result;
    }

    
}
View Code

  在建立實體類時,屬性最好使用包裝類,例如:Integer,由於與基本類型(int)相比,包裝類多了一種null狀態。能夠表示不存在,而基本類型帶有默認值(如int默認0),這時就會有歧義,不知道是值爲0仍是不存在。

  建立Hibernate配置文件

  在項目鼠標右鍵-new-SourceFolder,建立一個資源文件。

  (資源文件是爲了方便咱們閱讀而設計的,當程序編譯後,全部的資源文件會進行合併最後所有放到classes文件中,因此咱們能夠經過classpath進行獲取)

  建立hibernate.cfg.xml文件(這個文件名是hibernate默認文件名,當程序啓動時,hibernate會自動在classpath中尋找名爲hibernate.cfg.xml的文件,若是不是這個名字,就須要後期手動指定,會比較麻煩

  下面咱們須要爲文件添加約束,那麼約束在哪裏呢?

  其實hibernate早已經爲咱們準備好了,打開hibernate核心包下的org.hibernate,最下面會有dtd文件

  

  雙擊打開hibernate-configuration-3.0.dtd文件(3.0向下兼容,4.0不向下兼容,因此要選擇3.0的文件),會發現,上面註釋裏說明了約束頭怎麼寫:

   

複製到配置文件中:

這時咱們寫一個<而後alt+?,會有提示標籤,什麼?你沒有?那能夠看看另外一篇博客

  配置文件的基本結構以下:

<?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標籤,一個數據庫對應一個SessionFactory標籤 -->
    <session-factory>
        <!-- 必須的配置的參數5個,4大參數,數據庫方言  -->
        <!--
        #hibernate.connection.driver_class com.mysql.jdbc.Driver
        #hibernate.connection.url jdbc:mysql:///test
        #hibernate.connection.username gavin
        #hibernate.connection.password 
        數據庫方言
        #hibernate.dialect org.hibernate.dialect.MySQLDialect
         -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///blog</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>
        <!-- 生成數據庫的表結構 
        (hbm2dd全稱hibernate mapping to db define language auto create)
        update 沒表會自動建立,有表添加數據。
            若是開發中間須要添加字段,能夠在實體類添加屬性。update會自動在數據庫添加字段,而且不改變原來數據庫值
        validate 校驗實體屬性和數據庫是否一致
        -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 映射配置文件,能夠在map配置文件右鍵copy qualified name-->
        <mapping resource="com/cky/domain/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

上面配置的屬性均可以在hibernate-release-4.3.11.Final\project\etc\hibernate.properties文件中找到

  建立mapping映射文件

關於mapping映射文件的一些默認的規則。

  一、Hibernate的mapping映射文件默認須要和實體類在同一文件夾中

  二、mapping映射文件默認命名規則:實體類名.hbm.xml。hbm(全稱:hibernate mapping)

User.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="com.cky.domain.User" table="user">
<!-- 配置id
    name實體類屬性,column表字段,若是同樣,column能夠省略。
 -->
    <id name="uId" column="u_id">
    <!-- 主鍵生成策略 -->
        <generator class="native"></generator>
    </id>
    <property name="uEmail" column="u_email"></property>
    <property name="uName" column="u_name"></property>
    <property name="uUsername" column="u_username"></property>
    <property name="uPassword" column="u_password"></property>
    <property name="uAge" column="u_age"></property>
    <property name="uDetail" column="u_detail"></property>
    <property name="uAvatar" column="u_avatar"></property>
    <property name="isAdmin" column="is_admin"></property>
    <property name="createtime" column="createtime"></property>
    <property name="updatetime" column="updatetime"></property>
</class>
</hibernate-mapping>
View Code

User實體類文件

package com.cky.domain;

import java.sql.Timestamp;

public class User {
    private Integer uId;
    private String uEmail;
    private String uName;
    private String uUsername;
    private String uPassword;
    private String uAge;
    private String uDetail;
    private String uAvatar;
    private String isAdmin;
    private Timestamp createtime;
    private Timestamp updatetime;

    public Integer getuId() {
        return uId;
    }

    public void setuId(Integer uId) {
        this.uId = uId;
    }

    public String getuEmail() {
        return uEmail;
    }

    public void setuEmail(String uEmail) {
        this.uEmail = uEmail;
    }

    public String getuName() {
        return uName;
    }

    public void setuName(String uName) {
        this.uName = uName;
    }

    public String getuUsername() {
        return uUsername;
    }

    public void setuUsername(String uUsername) {
        this.uUsername = uUsername;
    }

    public String getuPassword() {
        return uPassword;
    }

    public void setuPassword(String uPassword) {
        this.uPassword = uPassword;
    }

    public String getuAge() {
        return uAge;
    }

    public void setuAge(String uAge) {
        this.uAge = uAge;
    }

    public String getuDetail() {
        return uDetail;
    }

    public void setuDetail(String uDetail) {
        this.uDetail = uDetail;
    }

    public String getuAvatar() {
        return uAvatar;
    }

    public void setuAvatar(String uAvatar) {
        this.uAvatar = uAvatar;
    }

    public String getIsAdmin() {
        return isAdmin;
    }

    public void setIsAdmin(String isAdmin) {
        this.isAdmin = isAdmin;
    }

    public Timestamp getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Timestamp createtime) {
        this.createtime = createtime;
    }

    public Timestamp getUpdatetime() {
        return updatetime;
    }

    public void setUpdatetime(Timestamp updatetime) {
        this.updatetime = updatetime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (uId != user.uId) return false;
        if (uEmail != null ? !uEmail.equals(user.uEmail) : user.uEmail != null) return false;
        if (uName != null ? !uName.equals(user.uName) : user.uName != null) return false;
        if (uUsername != null ? !uUsername.equals(user.uUsername) : user.uUsername != null) return false;
        if (uPassword != null ? !uPassword.equals(user.uPassword) : user.uPassword != null) return false;
        if (uAge != null ? !uAge.equals(user.uAge) : user.uAge != null) return false;
        if (uDetail != null ? !uDetail.equals(user.uDetail) : user.uDetail != null) return false;
        if (uAvatar != null ? !uAvatar.equals(user.uAvatar) : user.uAvatar != null) return false;
        if (isAdmin != null ? !isAdmin.equals(user.isAdmin) : user.isAdmin != null) return false;
        if (createtime != null ? !createtime.equals(user.createtime) : user.createtime != null) return false;
        if (updatetime != null ? !updatetime.equals(user.updatetime) : user.updatetime != null) return false;

        return true;
    }

    @Override
    public String toString() {
        return "User{" +
                "uId=" + uId +
                ", uEmail='" + uEmail + '\'' +
                ", uName='" + uName + '\'' +
                ", uUsername='" + uUsername + '\'' +
                ", uPassword='" + uPassword + '\'' +
                ", uAge='" + uAge + '\'' +
                ", uDetail='" + uDetail + '\'' +
                ", uAvatar='" + uAvatar + '\'' +
                ", isAdmin='" + isAdmin + '\'' +
                ", createtime=" + createtime +
                ", updatetime=" + updatetime +
                "}\n";
    }

    @Override
    public int hashCode() {
        Integer result = uId;
        result = 31 * result + (uEmail != null ? uEmail.hashCode() : 0);
        result = 31 * result + (uName != null ? uName.hashCode() : 0);
        result = 31 * result + (uUsername != null ? uUsername.hashCode() : 0);
        result = 31 * result + (uPassword != null ? uPassword.hashCode() : 0);
        result = 31 * result + (uAge != null ? uAge.hashCode() : 0);
        result = 31 * result + (uDetail != null ? uDetail.hashCode() : 0);
        result = 31 * result + (uAvatar != null ? uAvatar.hashCode() : 0);
        result = 31 * result + (isAdmin != null ? isAdmin.hashCode() : 0);
        result = 31 * result + (createtime != null ? createtime.hashCode() : 0);
        result = 31 * result + (updatetime != null ? updatetime.hashCode() : 0);
        return result;
    }

    
}
View Code

  添加測試

package com.cky.Demo;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.cky.domain.User;
import com.cky.utils.HibernateUtils;

public class DemoTest {
    @Test
    public void testSave() {
        //1.加載配置文件
        Configuration cfg=new Configuration();
        //默認加載src目錄下的hibernate.cfg.xml的配置文件
        cfg.configure();
        //2.建立sessionFactory
        SessionFactory sessionFactory = cfg.buildSessionFactory();
        //3.建立session
        Session session = sessionFactory.openSession();
        //4.開啓事務
        Transaction tr = session.beginTransaction();
        //5.編寫更新代碼
        User user=new User();
        user.setuName("小紅");
        user.setuPassword("123456");
        session.save(user);
        
        //6.提交事務
        tr.commit();
        //7.釋放資源
        session.close();
        sessionFactory.close();
    }
}
相關文章
相關標籤/搜索