Hibernate基礎之增刪改查

注意:在從SessionFactory獲取Session時,有兩種方式,
第一種是:sessionFactory.openSession(),獲取一個新的session,這是沒有與本地進行綁定的session
第二種是:sessionFactory.getCurrentSession(),獲取一個當前線程並與本地進行綁定,類似於銀行系統中的轉賬業務建議使用此方式。但注意這個方法須要在配置文件中進行配置,並且手動啓動事務並進行提交,否則會報錯。

1、創建一個JAVA項目

2、導入Hibernate的相關JAR包

這裏寫圖片描述

3、創建數據庫:hibernate_test

4、在數據庫創建user表

USE `hibernate_test`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(20) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

5、創建User.class實體類

package com.ckinghan.bean;

public class User {

    private int id;

    private String userName;

    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password="
                + password + "]";
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


}

6、在User.class目錄下創建User.hbm.xml的Hibernate的映射文件

<?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.ckinghan.bean.User" table="user">

            <!-- ID映射的字段 -->
            <id name="id" column="id">
                <!-- hibernate根據使用的數據庫自行判斷採用   identity、hilo、sequence   其中一種作爲主鍵生成方式 -->
                <generator class="native"></generator>
            </id>

            <!-- 實體類中的userName與表中的userName對應 -->
            <property name="userName" column="userName"/>

            <!-- 實體類中的password與表中的password字段對應 -->
            <property name="password" column="password"/>

        </class>

    </hibernate-mapping>

7、在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 name="foo">
        <!-- 配置數據庫連接 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_test</property>

        <!-- 在控制檯顯示SQL語句 -->
        <property name="show_sql">true</property>
        <!-- 格式化SQL語句 -->
        <property name="format_sql">true</property>
        <!-- 自動創建|更新|驗證數據庫表結構 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 事務自動提交 -->
        <property name="hibernate.connection.autocommit">true</property> 
        <!-- 將獲取的當前線程與本地進行綁定,以確認所操作的session是同一個 -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- 映射文件的地址 -->
        <mapping resource="com/ckinghan/bean/User.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

8、創建測試類

package com.ckinghan.test;

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

import com.ckinghan.bean.User;
/**
 * hibernate測試類
 * @author ckinghan
 */
public class HibernateTest {

    /**
     * 測試Hibernate的數據存儲
     * session通過openSession()方法獲取,此方法不能保證當前connection唯一
     * 在類似於轉賬之類的業務中,無法使用。
     */
    @Test
    public void testHibernateSave(){
        //1、加載配置文件,如果hibernate的配置文件名是hibernate.cfg.xml,並且放置在src目錄下,可以自動加載
        Configuration configuration = new Configuration().configure();
        //2、通過configuration創建sessionFactory
        SessionFactory buildSessionFactory = configuration.buildSessionFactory();
        //3、通過sessionFactory創建Session,注意:這裏的Session是hibernate下的session
        Session openSession = buildSessionFactory.openSession();
        //4、使用save保存數據
        User user = new User();
        user.setPassword("password123");
        user.setUserName("userName");
        openSession.save(user);
        //5、關閉連接
        openSession.close();
        buildSessionFactory.close();
    }


    /**
     * 測試Hibernate的數據存儲
     * session通過getCurrentSession()方法獲取,此方法可以保證當前connection唯一
     * 建議使用,但注意使用getCurrentSession時,。
     */
    @Test
    public void testHibernateSave1(){

        //1、加載配置文件,如果hibernate的配置文件名是hibernate.cfg.xml,並且放置在src目錄下,可以自動加載
        Configuration configuration = new Configuration().configure();
        //2、通過configuration創建sessionFactory
        SessionFactory buildSessionFactory = configuration.buildSessionFactory();
        /**
         * 3、通過sessionFactory創建Session,注意:這裏的Session是hibernate下的session
         * getCurrentSession();方法,將當前線程與本地進行綁定,可以確保操作的session(connection)不會變,
         * 相當於ThreadLocal<connection>,建議使用此方法,但在使用此方法前,必須在hibernate.cfx.xml配置文件
         * 中進行以下配置:
         * <property name="hibernate.current_session_context_class">thread</property>
         * 並且手動啓動事務並提交,否則會報錯
         */
        Session openSession = buildSessionFactory.getCurrentSession();
        //開啓事務,因爲使用了getCurrentSession,這裏要手動提交事務
        Transaction transaction = openSession.beginTransaction();
        //4、使用save保存數據
        User user = new User();
        user.setPassword("password123");
        user.setUserName("userName");
        openSession.save(user);
        //提交事務
        transaction.commit();
        //5、關閉連接
        /**
         * 在commit()時就已經關閉,這裏不用重新關閉
         * openSession.close();      
         */
        buildSessionFactory.close();
    }

    /**
     * 查詢用戶信息
     */
    @Test
    public void hibernateSelect(){
        Configuration configuration = new Configuration().configure();
        SessionFactory buildSessionFactory = configuration.buildSessionFactory();
        //獲取當前事務
        Session currentSession = buildSessionFactory.getCurrentSession();
        //啓動事務
        Transaction transaction = currentSession.beginTransaction();

        //根據id主鍵查詢數據
        Object object = currentSession.get(User.class, 1);
        //如果查詢出來的數據不爲空,說明查詢到了數據
        if(object != null && !"".equals(object)){
            User user = (User) object;
            //打印查詢出的用戶信息
            System.out.println(user);
        }else{
            System.out.println("未查詢到用戶ID爲1的數據");
        }

        //提交事務
        transaction.commit();
        //關閉事務
        buildSessionFactory.close();
    }

    /**
     * 更新用戶信息
     */
    @Test
    public void hibernateEdit(){
        Configuration configuration = new Configuration().configure();
        SessionFactory buildSessionFactory = configuration.buildSessionFactory();
        //獲取當前線程
        Session currentSession = buildSessionFactory.getCurrentSession();
        //啓動事務
        Transaction beginTransaction = currentSession.beginTransaction();

        //查詢用戶
        Object object = currentSession.get(User.class, 2);
        //如果用戶存在
        if(object != null && !"".equals(object)){
            User user = (User) object;
            //更新用戶名爲:測試用戶
            user.setUserName("測試用戶");
            //更新數據庫中的數據
            currentSession.update(user);
            System.out.println("更新用戶信息成功");
        }else{
            System.out.println("用戶不存在,更新失敗");
        }

        //提交事務
        beginTransaction.commit();
        //關閉連接
        buildSessionFactory.close();
    }

    /**
     * 刪除數據
     */
    @Test
    public void hibernateDelete(){
        Configuration configuration = new Configuration().configure();
        SessionFactory buildSessionFactory = configuration.buildSessionFactory();
        //獲取當前線程
        Session currentSession = buildSessionFactory.getCurrentSession();
        //啓動事務
        Transaction transaction = currentSession.beginTransaction();
        //查詢用戶信息
        Object object = currentSession.get(User.class, 3);

        //如果查詢到了數據,
        if(object != null && !"".equals(object)){
            //則將數據轉換爲User實體類
            User user = (User) object;

            //刪除用戶信息
            currentSession.delete(user);
            System.out.println("用戶信息刪除成功");
        }else{
            System.out.println("用戶不存在,刪除失敗");
        }

        //提交事務
        transaction.commit();
        //關閉連接
        buildSessionFactory.close();
    }
}

9、執行測試類中的testHibernateSave/testHibernateSave1方法添加數據方法4次,添加4條記錄,結果如下:

這裏寫圖片描述

10、執行hibernateSelect()查詢用戶信息方法如下:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: 
    select
        user0_.id as id0_0_,
        user0_.userName as userName0_0_,
        user0_.password as password0_0_ 
    from
        user user0_ 
    where
        user0_.id=?
User [id=1, userName=userName, password=password123]

11、執行hibernateEdit()更新用戶信息方法如下:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: 
    select
        user0_.id as id0_0_,
        user0_.userName as userName0_0_,
        user0_.password as password0_0_ 
    from
        user user0_ 
    where
        user0_.id=?
更新用戶信息成功
Hibernate: 
    update
        user 
    set
        userName=?,
        password=? 
    where
        id=?

這裏寫圖片描述

這裏我沒有指定utf-8編碼出現 了亂碼,如果指定了,不會出現這個問題的。

12、執行hibernateDelete()刪除方法如下 :

Hibernate: 
    select
        user0_.id as id0_0_,
        user0_.userName as userName0_0_,
        user0_.password as password0_0_ 
    from
        user user0_ 
    where
        user0_.id=?
用戶信息刪除成功
Hibernate: 
    delete 
    from
        user 
    where
        id=?

注意,因爲代碼中,我把輸出的“用戶信息刪除成功”放到了事務中,而數據庫中的SQL語句在未提交前,是不會輸出執行的,所以就出現了提示信息在前的問題
發佈了153 篇原創文章 · 獲贊 69 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章