溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在Hibernate中實現(xiàn)CRUD操作

發(fā)布時間:2021-06-08 17:00:04 來源:億速云 閱讀:163 作者:Leah 欄目:編程語言

這篇文章給大家介紹如何在Hibernate中實現(xiàn)CRUD操作,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

一、Hibernate是什么

Hibernate是一個開放源代碼的對象關(guān)系映射框架,它對JDBC進(jìn)行了非常輕量級的對象封裝,它將POJO與數(shù)據(jù)庫表建立映射關(guān)系,是一個全自動的orm框架,hibernate可以自動生成SQL語句,自動執(zhí)行,使得Java程序員可以隨心所欲的使用對象編程思維來操縱數(shù)據(jù)庫。 Hibernate可以應(yīng)用在任何使用JDBC的場合,既可以在Java的客戶端程序使用,也可以在Servlet/JSP的Web應(yīng)用中使用,最具革命意義的是,Hibernate可以在應(yīng)用EJB的JaveEE架構(gòu)中取代CMP,完成數(shù)據(jù)持久化的重任(這里引用百度的描述)

二、為什么要使用Hibernate

為什么要使用Hibernate,先不回答為什么要使用它,因為一項技術(shù)入世,一定有其應(yīng)用的場景。

那么Hibernate的優(yōu)點有哪些呢?

(1)標(biāo)準(zhǔn)的orm框架,程序員不需要編寫SQL語句

(2)具有良好的數(shù)據(jù)庫無關(guān)性,即數(shù)據(jù)庫發(fā)生變化的話,代碼無需再次編寫;

任何事情有利也有弊

那么Hibernate的缺點有哪些呢?

(1)學(xué)習(xí)門檻高,需要對數(shù)據(jù)關(guān)系模型有良好的基礎(chǔ),而且在設(shè)置OR映射的時候,需要考慮好性能和對象模型的權(quán)衡;

(2)程序員不能自主的去進(jìn)行SQL性能優(yōu)化;

那么Hibernate的應(yīng)用場景有哪些呢?

例如需求明確、業(yè)務(wù)固定的項目,比如OA項目、ERP、CRM等項目

三、Hibernate的基礎(chǔ)實例

記得很久之前在初學(xué)Hibernate時,雖然網(wǎng)上有不少例子,但是我覺得都不是我想要的,因為很殘缺不是特別系統(tǒng),但是如果太系統(tǒng)化的話,必然會連載,但是我覺得對于初學(xué)者而言,有些時候看連載確實有點昏昏欲睡,沒意思。這次實例是以maven工程作為示例,maven是當(dāng)前最流行的項目管理工具之一。

接下來示例演示與說明:

1.導(dǎo)入maven依賴

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>cn.example</groupId>
 <artifactId>hibernate-crud</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 
  <dependencies>
    <!--hibernate -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.11.Final</version>
    </dependency>
    <!--MySQL數(shù)據(jù)庫 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.44</version>
    </dependency>
    <!--junit單元測試 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <!-- 指定jdk版本 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

2.編寫hibernate的主要配置文件

hibernate.cfg.xml

<!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/blog_test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">1234</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="current_session_context_class">thread</property> 
    <mapping resource="mapping/User.hbm.xml"></mapping>
  </session-factory>
</hibernate-configuration>

數(shù)據(jù)庫四要素:加載驅(qū)動、建立連接、用戶名、密碼。這些我就不多說了。

hibernate.dialect:數(shù)據(jù)庫方言 hibernate的良好的可移植性就在這里體現(xiàn),面對不同的數(shù)據(jù)庫只需改方言即可適用

hibernate.show_sql:是否打印SQL語句 開發(fā)環(huán)境建議 生產(chǎn)環(huán)境不建議

hibernate.hbm2ddl.auto: 一般建議使用update 而不是使用create

current_session_context_class:這里主要針對session對象,后面我會有針對性地講解

3.編寫實體

User.java

package cn.blog.entity;


import java.io.Serializable;
import java.util.Date;


public class User implements Serializable{

  private static final long serialVersionUID = 1L;

  /**
   * 用戶主鍵
   */
  private Integer userId;
  /**
   * 用戶編碼(登錄賬戶) 手機號 郵箱號
   */
  private String loginCode;
  /**
   * 用戶名
   */
  private String userName;
  /**
   * 密碼
   */
  private String password;
  /**
   * 性別
   */
  private Integer sex;
  /**
   * 身份證
   */
  private String identityCard;
  /**
   * 創(chuàng)建時間
   */
  private String createTime;
  /**
   * 創(chuàng)建人
   */
  private String createBy;
  /**
   * 更新時間
   */
  private String updateTime;
  /**
   * 更新人
   */
  private String updateBy;
  /**
   * 狀態(tài):0注冊新用戶 1郵件認(rèn)證用戶 2管理員 3黑名單
   */
  private Integer status;


  public Integer getUserId() {
    return userId;
  }

  public void setUserId(Integer userId) {
    this.userId = userId;
  }

  public String getLoginCode() {
    return loginCode;
  }

  public void setLoginCode(String loginCode) {
    this.loginCode = loginCode;
  }

  public String getUserName() {
    return userName;
  }

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

  public String getPassword() {
    return password;
  }

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

  public Integer getSex() {
    return sex;
  }

  public void setSex(Integer sex) {
    this.sex = sex;
  }

  public String getIdentityCard() {
    return identityCard;
  }

  public void setIdentityCard(String identityCard) {
    this.identityCard = identityCard;
  }

  public String getCreateTime() {
    return createTime;
  }

  public void setCreateTime(String createTime) {
    this.createTime = createTime;
  }

  public String getCreateBy() {
    return createBy;
  }

  public void setCreateBy(String createBy) {
    this.createBy = createBy;
  }

  public String getUpdateTime() {
    return updateTime;
  }

  public void setUpdateTime(String updateTime) {
    this.updateTime = updateTime;
  }

  public String getUpdateBy() {
    return updateBy;
  }

  public void setUpdateBy(String updateBy) {
    this.updateBy = updateBy;
  }

  public Integer getStatus() {
    return status;
  }

  public void setStatus(Integer status) {
    this.status = status;
  }

 
  @Override
  public String toString() {
    return "User{" +
    "userId=" + userId +
    ", loginCode=" + loginCode +
    ", userName=" + userName +
    ", password=" + password +
    ", sex=" + sex +
    ", identityCard=" + identityCard +
    ", createTime=" + createTime +
    ", createBy=" + createBy +
    ", updateTime=" + updateTime +
    ", updateBy=" + updateBy +
    ", status=" + status +
    "}";
  }
}

4.編寫實體對應(yīng)的映射文件

User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="cn.blog.entity.User" table="user">
    <id name="userId" type="java.lang.Integer">
      <column name="user_id"/>
      <generator class="identity" />
    </id>
    <!-- 映射CrUser類中的code屬性 -->
    <property name="loginCode" type="string">
      <column name="login_code" length="10" not-null="true" unique="true" />
    </property>
    <property name="userName" type="string">
      <column name="user_name" length="20" not-null="true" unique="true" />
    </property>
     <property name="password" type="string">
      <column name="password" length="20" not-null="true" unique="true" />
    </property>

    
    <property name="sex" type="java.lang.Integer">
      <column name="sex" length="20" not-null="true" unique="true" />
    </property>
    
      
    <property name="identityCard" type="string">
      <column name="identity_card" length="20" not-null="true" unique="true" />
    </property>
    
      
    <property name="createTime" type="string">
      <column name="create_time" length="20" not-null="true" unique="true" />
    </property>
    
      
    <property name="createBy" type="string">
      <column name="create_by" length="20" not-null="true" unique="true" />
    </property>
    
      
    <property name="updateTime" type="string">
      <column name="update_time" length="20" not-null="true" unique="true" />
    </property>
    
    <property name="updateBy" type="string">
      <column name="update_by" length="20" not-null="true" unique="true" />
    </property>
    
    <property name="status" type="java.lang.Integer">
      <column name="status" length="20" not-null="true" unique="true" />
    </property>
    
  </class>
</hibernate-mapping>

column中的name屬性作用:主要是使對象實體與表映射

type:實體屬性

length:長度

not-null:是否為空 默認(rèn)為false 不為空

unique 獨特的唯一的

5.封裝工具類

HibernateUtils.java

package cn.blog.utils;

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

public class HibernateUtil extends Object{
  private static SessionFactory sessionFactory;
  static
  {
    try{
      Configuration configuration=new Configuration().configure();
      sessionFactory = configuration.buildSessionFactory();
     }catch (Throwable ex){
        throw new ExceptionInInitializerError(ex);
    }
  }
   private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }  
  public static Session getSession() throws HibernateException
  {
    Session session = (Session) threadLocal.get();
    if (session == null){
      session = sessionFactory.openSession();
      threadLocal.set(session);
    }
      return session;
  }
  public static void closeSession() throws HibernateException {
    Session session = (Session) threadLocal.get();
    if (session != null)
      session.close();
    threadLocal.set(null);
  }
  
  public static void shutdown(){
    getSessionFactory().close();
  }
  
}

6.編寫測試類

下面就是具體的crud操作 有部分注釋了,只需去除注釋即可測驗效果。

package cn.blog.test;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import cn.blog.entity.User;
import cn.blog.utils.HibernateUtil;

public class BlogTest {

  public static void main(String[] args) {
    //刪除數(shù)據(jù)
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    User user = new User();
    user.setUserId(2);
    user.setLoginCode("yc@163.com");
    user.setUserName("聰哥哥");
    user.setPassword("test123");
    user.setIdentityCard("1234");
    user.setCreateBy("系統(tǒng)");
    user.setCreateTime("2018-10-21 10:00");
    user.setUpdateBy("系統(tǒng)");
    user.setUpdateTime("2018-10-21 10:00");
    user.setSex(1);
    user.setStatus(1);
    session.delete(user);
    tx.commit();
    
    
  /** 
     根據(jù)主鍵查詢單條數(shù)據(jù)
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
        User user = (User) session.get(User.class, 1);
        System.out.println(user.getUserName());
        
        tx.commit();
    } catch (Exception e) {
      e.printStackTrace();
      tx.rollback();
    }finally {
      HibernateUtil.closeSession();
    }
   
    */
    
    
  /*  
    更新數(shù)據(jù)
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
      User user = new User();
      user.setUserId(2);
      user.setLoginCode("yc@163.com");
      user.setUserName("聰哥哥");
      user.setPassword("test123");
      user.setIdentityCard("1234");
      user.setCreateBy("系統(tǒng)");
      user.setCreateTime("2018-10-21 10:00");
      user.setUpdateBy("系統(tǒng)");
      user.setUpdateTime("2018-10-21 10:00");
      user.setSex(1);
      user.setStatus(1);
      
      session.saveOrUpdate(user);
      System.out.println("update succes");
      tx.commit();
        
    } catch (Exception e) {
      e.printStackTrace();
      tx.rollback();
       System.out.println("update fail");
    }finally {
      HibernateUtil.closeSession();
    }
    
    */
    
    
/*   
    模糊查詢數(shù)據(jù)
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    
    String userName="Y";
    Criteria c= session.createCriteria(User.class);
    c.add(Restrictions.like("userName", "%"+userName+"%"));
    
    List<User> user = c.list();
     for (User user2 : user) {
      System.out.println(user2.getUserName());
    }
    tx.commit();
  */
    
    
    /*

     新增數(shù)據(jù)
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();
    try {
      
      User user = new User();
      user.setLoginCode("yc@163.com");
      user.setUserName("Y先生");
      user.setPassword("test123");
      user.setIdentityCard("1234");
      user.setCreateBy("系統(tǒng)");
      user.setCreateTime("2018-10-21 10:00");
      user.setUpdateBy("系統(tǒng)");
      user.setUpdateTime("2018-10-21 10:00");
      user.setSex(1);
      user.setStatus(1);
      session.save(user);
      System.out.println("insert data success");
      tx.commit();
    } catch (Exception e) {
      e.printStackTrace();
      tx.rollback();
      System.out.println("insert data fail");
    }finally {
      
      HibernateUtil.closeSession();
    }*/
  }
}

小結(jié):

本文代碼放置處為:https://github.com/youcong1996/study_simple_demo.git

分支為hibernate-crud分支

如果在復(fù)用我的這篇文章在實際遇到較多的問題而無法解決,可直接clone我的git倉庫本地運行

如圖所示:

如何在Hibernate中實現(xiàn)CRUD操作

關(guān)于如何在Hibernate中實現(xiàn)CRUD操作就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI