您的位置:首页 > 其它

Hibernate之CRUD实践

2018-10-22 19:52 555 查看

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(); }*/ } }

 

小结:

本文代码放置处为:https://github.com/youcong1996/study_simple_demo.git

分支为hibernate-crud分支

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

如图所示:

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: