一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - Hibernate之CRUD操作實踐

Hibernate之CRUD操作實踐

2021-06-09 14:11挑戰者V Java教程

這篇文章主要介紹了Hibernate之CRUD操作實踐,本文主要告訴讀者Hibernate是什么,為什么要使用HibernateHibernate的優缺點,Hibernate的基礎實例應用。需要的朋友可以參考下

hibernate作為一個高度封裝的持久層框架,曾經是非常牛逼的,現在雖然應用不是特別廣,比如我前公司主要是做oa的,應用的框架就是spring+springmvc+hibernate。

hibernate與mybatis相比,雖然應用面不是特別廣,但是并不代表就沒有用武之地。

今天講講hibernate的crud,本文主要告訴讀者hibernate是什么,為什么要使用hibernatehibernate的優缺點,hibernate的基礎實例應用。

一、hibernate是什么

hibernate是一個開放源代碼的對象關系映射框架,它對jdbc進行了非常輕量級的對象封裝,它將pojo與數據庫表建立映射關系,是一個全自動的orm框架,hibernate可以自動生成sql語句,自動執行,使得java程序員可以隨心所欲的使用對象編程思維來操縱數據庫。 hibernate可以應用在任何使用jdbc的場合,既可以在java的客戶端程序使用,也可以在servlet/jsp的web應用中使用,最具革命意義的是,hibernate可以在應用ejb的javeee架構中取代cmp,完成數據持久化的重任(這里引用百度的描述)

二、為什么要使用hibernate

為什么要使用hibernate,先不回答為什么要使用它,因為一項技術入世,一定有其應用的場景。

那么hibernate的優點有哪些呢?

(1)標準的orm框架,程序員不需要編寫sql語句

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

任何事情有利也有弊

那么hibernate的缺點有哪些呢?

(1)學習門檻高,需要對數據關系模型有良好的基礎,而且在設置or映射的時候,需要考慮好性能和對象模型的權衡;

(2)程序員不能自主的去進行sql性能優化;

那么hibernate的應用場景有哪些呢?

例如需求明確、業務固定的項目,比如oa項目、erp、crm等項目

三、hibernate的基礎實例

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

接下來示例演示與說明:

1.導入maven依賴

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<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數據庫 -->
    <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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!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>

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

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

hibernate.show_sql:是否打印sql語句 開發環境建議 生產環境不建議

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

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

3.編寫實體

user.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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;
  /**
   * 創建時間
   */
  private string createtime;
  /**
   * 創建人
   */
  private string createby;
  /**
   * 更新時間
   */
  private string updatetime;
  /**
   * 更新人
   */
  private string updateby;
  /**
   * 狀態:0注冊新用戶 1郵件認證用戶 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.編寫實體對應的映射文件

user.hbm.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?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:是否為空 默認為false 不為空

unique 獨特的唯一的

5.封裝工具類

hibernateutils.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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操作 有部分注釋了,只需去除注釋即可測驗效果。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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) {
    //刪除數據
    session session = hibernateutil.getsession();
    transaction tx = session.begintransaction();
    user user = new user();
    user.setuserid(2);
    user.setlogincode("[email protected]");
    user.setusername("聰哥哥");
    user.setpassword("test123");
    user.setidentitycard("1234");
    user.setcreateby("系統");
    user.setcreatetime("2018-10-21 10:00");
    user.setupdateby("系統");
    user.setupdatetime("2018-10-21 10:00");
    user.setsex(1);
    user.setstatus(1);
    session.delete(user);
    tx.commit();
    
    
  /**
     根據主鍵查詢單條數據
    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();
    }
   
    */
    
    
  /* 
    更新數據
    session session = hibernateutil.getsession();
    transaction tx = session.begintransaction();
    try {
      user user = new user();
      user.setuserid(2);
      user.setlogincode("[email protected]");
      user.setusername("聰哥哥");
      user.setpassword("test123");
      user.setidentitycard("1234");
      user.setcreateby("系統");
      user.setcreatetime("2018-10-21 10:00");
      user.setupdateby("系統");
      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();
    }
    
    */
    
    
/*  
    模糊查詢數據
    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();
  */
    
    
    /*
 
     新增數據
    session session = hibernateutil.getsession();
    transaction tx = session.begintransaction();
    try {
      
      user user = new user();
      user.setlogincode("[email protected]");
      user.setusername("y先生");
      user.setpassword("test123");
      user.setidentitycard("1234");
      user.setcreateby("系統");
      user.setcreatetime("2018-10-21 10:00");
      user.setupdateby("系統");
      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();
    }*/
  }
}

小結:

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

分支為hibernate-crud分支

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

如圖所示:

Hibernate之CRUD操作實踐

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:http://www.cnblogs.com/youcong/p/9832283.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 99国产牛牛视频在线网站 | 日韩精品欧美激情国产一区 | 午夜一区二区免费视频 | 欧美日韩精品在线视频 | 欧美日韩三区 | 天天久久影视色香综合网 | 3344在线看片| a级片在线观看免费 | 男人把j放进女人的p里视频 | 国产卡一卡二卡三乱码手机 | 福利视频一区二区思瑞 | 美女林柏欣21p人体之仓之梦 | 欧美疯狂做爰xx | 动漫美女3d被爆漫画 | 麻豆天美精东果冻传媒在线 | 国产91第一页 | 免费视频一级片 | 亚洲入口 | 户外露出野战hd | 女同全黄h全肉动漫 | 亚洲精品视频导航 | 免费精品一区二区三区在线观看 | 欧美一级xxxx俄罗斯一级 | 京东热dj6666 | 韩国三级在线高速影院 | 欧美灰丝袜丝交nylons | 不卡视频一区二区 | 成人在线免费观看 | 超爽人人做人人爽 | 欧美肥胖老妇做爰变态 | 国产精品资源在线观看网站 | 二区三区不卡不卡视频 | 97福利社| 亚洲精品国产成人7777 | 韩剧消失的眼角膜免费完整版 | 99热这里只有精品久久免费 | free嫩白的12sex性自由 | 2022日韩理论片在线观看 | 男人猛戳女人下部30分钟 | 国产经典一区 | 成年人视频免费在线观看 |