当前位置: 移动技术网 > IT编程>开发语言>Java > Hibernate之CRUD操作实践

Hibernate之CRUD操作实践

2019年07月19日  | 移动技术网IT编程  | 我要评论

奈何天生郭奉孝,重生之喜乐大清,hxtk

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依赖

<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

<!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

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

<?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

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) {
    //删除数据
    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();
    }*/
  }
}

小结:

本文代码放置处为:

分支为hibernate-crud分支

如果在复用我的这篇文章在实际遇到较多的问题而无法解决,可直接clone我的git仓库本地运行

如图所示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网