Hibernate 基础配置及常用功能(一)
本来是想等全部框架测试完以后再统一发布的,但是随着测试的一点点增加感觉把需要叙述的东西放在一起终将会是一场灾难。所以还是打算分成几章来描述,其中还包括一些有待解决的问题。短期很难腾出时间来仔细阅读Hibernate 5.x以后版本的官方文档,只能先记录下来。
首先声明一点,我在写这篇文章的时候结合了5.0.6和4.3.11两个版本,结果发现新版有不少变化,一些在4.3.11中正常的功能在新版本之中有很大不同。
一、通过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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.learnhow</groupId>
<artifactId>Hibernate_Demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Hibernate_Demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- 引入新版依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.6.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Hibernate官方推荐的数据库连接池是c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.6.Final</version>
</dependency>
</dependencies>
<build>
<finalName>Hibernate5_Demo</finalName>
</build>
</project>
pom.xml
以上的配置中加入了对c3p0数据源的依赖,实际使用中却很少使用。因为在生产环境中,更主流的配置方法是通过Spring来结合各个模块,因此数据源也是在Spring中配置的。更何况现在国内比较流行使用alibaba的druid。
下面提供的是4.11.3版本的依赖,就是核心版本和c3p0版本号变了一下,其他都一样。
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.learnhow</groupId>
<artifactId>Hibernate_Demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Hibernate_Demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- 引入4.x版本依赖包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 这里配置的c3p0数据源最好和你所使用的hibernate版本一致 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
<build>
<finalName>Hibernate4_Demo</finalName>
</build>
</project>
pom.xml
二、配置hibernate.cfg.xml文件
<?xml version='1.0' encoding='utf-8'?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/learnhow</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 数据源配置中只要使用了hibernate.c3p0.前缀,Hibernate就会调用c3p0数据源 -->
<!-- 连接池中保留的最小连接数 -->
<property name="hibernate.c3p0.min_size">5</property>
<!-- 连接池中保留的最大连接数 -->
<property name="hibernate.c3p0.max_size">10</property>
<!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
<property name="hibernate.c3p0.timeout">1800</property>
<!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数 -->
<property name="hibernate.c3p0.acquire_increment">3</property>
<!-- SQL 数据库方言,配置数据库类型 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- session交给hibernate管理 -->
<property name="current_session_context_class">thread</property>
<!-- 是否显示sql语句 -->
<property name="show_sql">true</property>
<!-- 是否对语句格式化输出 -->
<property name="format_sql">true</property>
<!-- 使用hibernate管理输出表的创建及设置创建模式 -->
<property name="hbm2ddl.auto">update</property> <!-- 用户配置 --> </session-factory>
</hibernate-configuration>
hibernate.cfg.xml
值得一提的是,网上有很多讲关于如何在Hibernate中配置c3p0数据源的文章,几乎90%都是错误的。原因是Hibernate4.x版本以后就更改了数据源的配置方式,但是官方文档并没有及时修改,因此大家都仅仅是翻译了一下。我在配置的时候参考了5.0.6版本中有关配置c3p0数据源的说明。原文如下:
5.1.2. Using c3p0 Important
To use this integration, the application must include the hibernate-c3p0 module jar (as well as its dependencies) on the classpath.
Hibernate also provides support for applications to use c3p0 connection pooling. When using this c3p0 support, a number of additional configuration settings are recognized. Transaction isolation of the Connections is managed by the ConnectionProvider itself. See Section 5.1.7, “ConnectionProvider support for transaction isolation setting”. Additional settings hibernate.connection.driver_class
The name of the JDBC Driver class to use hibernate.connection.url
The JDBC connection url. Any settings prefixed with hibernate.connection. (other than the "special ones")
These all have the hibernate.connection. prefix stripped and the rest will be passed as JDBC connection properties hibernate.c3p0.min_size or c3p0.minPoolSize
The minimum size of the c3p0 pool. See http://www.mchange.com/projects/c3p0/#minPoolSize hibernate.c3p0.max_size or c3p0.maxPoolSize
The maximum size of the c3p0 pool. See http://www.mchange.com/projects/c3p0/#maxPoolSize hibernate.c3p0.timeout or c3p0.maxIdleTime
The Connection idle time. See http://www.mchange.com/projects/c3p0/#maxIdleTime hibernate.c3p0.max_statements or c3p0.maxStatements
Controls the c3p0 PreparedStatement cache size (if using). See http://www.mchange.com/projects/c3p0/#maxStatements hibernate.c3p0.acquire_increment or c3p0.acquireIncrement
Number of connections c3p0 should acquire at a time when pool is exhauted. See http://www.mchange.com/projects/c3p0/#acquireIncrement hibernate.c3p0.idle_test_period or c3p0.idleConnectionTestPeriod
Idle time before a c3p0 pooled connection is validated. See http://www.mchange.com/projects/c3p0/#idleConnectionTestPeriod c3p0.initialPoolSize
The initial c3p0 pool size. If not specified, default is to use the min pool size. See http://www.mchange.com/projects/c3p0/#initialPoolSize Any other settings prefixed with hibernate.c3p0.
Will have the hibernate. portion stripped and be passed to c3p0. Any other settings prefixed with c3p0.
Get passed to c3p0 as is. See http://www.mchange.com/projects/c3p0/#configuration
Using c3p0
大意就是配置c3p0数据源首先需要引入相关依赖,然后只需要在配置文件中增加的任何一条语句是以hibernate.c3p0.为前缀,Hibernate就会默认使用c3p0管理数据库。
如果不需要配置第三方数据源也可以使用Hibernate直接操作数据库,只需要把有关c3p0的配置删掉就可以了。
<?xml version='1.0' encoding='utf-8'?>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/learnhow</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC连接池,开发环境设置1就可以了 -->
<property name="connection.pool_size">1</property>
<!-- 数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- session交给hibernate管理 -->
<property name="current_session_context_class">thread</property>
<!-- 是否显示sql语句 -->
<property name="show_sql">true</property>
<!-- 是否对语句格式化输出 -->
<property name="hbm2ddl.auto">update</property> </session-factory>
</hibernate-configuration>
hibernate.cfg.xml
三、获取SessionFactory
使用过Hibernate3.x版本的大概都知道,Hibernate是通过SessionFactory作为管理接口的。在4.x版本后,官方提供了一个新的配置方法,即所有的操作都必须首先在StandardServiceRegistry中注册。具体方法如下:
package util; import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() {
try{
Configuration configuration = new Configuration().configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
} public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
HibernateUtil4.java
但是在5.x版本中,官方又更改了获取SessionFactory的方法,我查了新版本的文档似乎并没有找到修改的原因和官方提供的获取SessionFactory的标准方法。以下我修改的代码:
package util; import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory(); public static SessionFactory getSessionFactory() {
return sessionFactory;
} private static SessionFactory buildSessionFactory() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
return sessionFactory;
} catch (Exception e) {
System.out.println(e);
StandardServiceRegistryBuilder.destroy(registry);
}
return null;
}
}
HibernateUtil5.java
以上三步基本可以完成对Hibernate的功能配置,不过实际使用中这样配置已经不多见了。
Hibernate 基础配置及常用功能(一)的更多相关文章
- Hibernate 基础配置及常用功能(三)
本章重点讲述Hibernate对象的三种状态以及如何配置二级缓存 有关Hibernate的三种状态如何相互转换网上都能查到,官方文档描述的也比较详细.这里主要是针对几个重点方法做代码演示. 一.状态转 ...
- Hibernate 基础配置及常用功能(二)
本章主要是描述几种经典映射关系,顺带比较Hibernate4.x和Hibernate5.x之间的区别. 一.建立测试工程目录 有关实体类之间的相互映射关系,Hibernate官方文档其实描述的非常详细 ...
- Hibernate学习笔记2.1(Hibernate基础配置)
Hibernate基础配置 1.<property name="hbm2ddl.auto">update</property> 在SessionFactor ...
- Fedora 28 系统基础配置以及常用软件安装方式
实验说明: 很多人说Linux很难用,很难上手,其实不然,倘若不玩游戏,其实很多发行版Linux都可以成为主力系统,就比如本章要讲的 Fedora 28.本章会从镜像来源.系统安装.基础配置和常用软件 ...
- JAVA基础语法:常用功能符以及循环结构和分支结构(转载)
3.JAVA基础语法:常用功能符以及循环结构和分支结构 1.常用功能符 注释 ("文字"是被注释的部分) //文字 单行注释 /文字/ 多行注释 算术运算符 + - * / / 整 ...
- Ansible基础配置与常用模块使用
环境介绍: Ansible服务端IP:192.168.2.215 Ansible客户端IP:192.168.2.216.192.168.2.218.192.168.2.113 一.创建Ansibl ...
- hibernate基础配置
数据库表名和类名 一致 注解:可写可不写: XML:可写可不写: <class name="Student"> 不一致 注解: public class Teache ...
- 3.Hibernate基础配置
1.Hibernate.cfg.xml:hbm2ddl.auto 在SessionFactory创建时,自动检查数据库结构,或者将数据库schema的DDL导出到数据库 <property na ...
- Hibernate学习笔记2.3(Hibernate基础配置)
映射,注释可以放在成员变量上面,也可以放在get方法上面 写在成员变量的话 破坏了java的面向对象思维 直接让hibernate访问内部的私有元素 要是能直接设指不合适哈哈 所以主张写在get方法上 ...
随机推荐
- oracle 11g RAC 补丁升级方法
一.自动升级方法 使用auto方式在两节点分别进行PSU的安装,安装PSU前注意更新opatch工具至PSU所要求版本,p22191577补丁包括GI和DB,分别执行即可. 两节点分别grid用户执行 ...
- asp.net mvc 表单相关
1. <form action="/controller/action" method="post"> ... </form> *act ...
- 微信小程序时代已经来临
昨天估计微信公众号上产生了第一篇最快的30万+文章,10万+只花了10多分钟.就是冯大辉(著名Oracle专家,知名博主)同学的「微信应用号来了」. 为什么这么一篇如此简单又技术类的文章一下能刷遍朋友 ...
- JAVA中使用FTPClient上传下载
Java中使用FTPClient上传下载 在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在c ...
- https://yq.aliyun.com/articles/65125?spm=5176.100240.searchblog.18.afqQoU
https://yq.aliyun.com/articles/65125?spm=5176.100240.searchblog.18.afqQoU
- Quartz2D 编程指南(四)位图与图像遮罩、CoreGraphics 绘制 Layer
概览 图形上下文 路径 颜色与颜色空间 变换 图案 阴影 渐变 透明层 Quartz 2D 中的数据管理 位图与图像遮罩 CoreGraphics 绘制 Layer 位图与图像遮罩 简介 位图与图像遮 ...
- log4j+mongodb
maven 配置: <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java ...
- http的一些事
查找资料将http中缓存相关的知识记录下 一般来说:Last-Modifed和Expires是一对,ETag和Cache-Control是一对 Last-Modified Client端跟Server ...
- 记在virtualbox下挂载共享文件夹的方法
sudo mount -t vboxsf share /usr/share sudo mount -t vboxsf 共享文件夹名称(在设置页面设置的) 挂载的目录
- ARM 开发工具 Keil和DS-5的比较。
http://www.eeboard.com/bbs/thread-25219-1-1.html 如今ARM体系架构的处理器在嵌入式市场上呼风唤雨,从低端的MCU应用到高端的多媒体消费电子,移动设备领 ...