服务器之家:专注于服务器技术及软件下载分享
分类导航

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("yc@163.com");
    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("yc@163.com");
      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("yc@163.com");
      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

延伸 · 阅读

精彩推荐