相关下载jar包csdn地址:http://download.csdn.net/download/zs20082012/10242310
一:下载hibernate相关jar包:下载地址:http://hibernate.org/orm/releases/,选择你需要的版本下载,下载完成之后解压找到lib文件夹,会有很多子文件夹,选择required文件夹,将下面的所有的jar包拷贝到javaweb项目下的web-inf下的lib目录下,设置构建路径ok,目前我用的是5.2.12相关的包
二:hibernate.cfg.xml配置文件放在哪里?
网上有很多介绍,但是我用的是eclipse环境开发javaweb项目,所以我的配置文件只是放在src根目录下ok
举例该配置文件代码:
<?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 元素用于配置Hibernate中的属性
键:值
-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">roots</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
<!-- show_sql: 操作数据库时,会 向控制台打印sql语句 -->
<property name="show_sql">true</property>
<!-- format_sql: 打印sql语句前,会将sql语句先格式化 -->
<property name="format_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- #4如何创建表(不重要)
create:每一次加载cfg.xml文件都将创建表,程序关闭时,表不进行删除 [初始化,测试时使用]
如果表存在则先删除后创建
create-drop:每一次加载cfg.xml文件都将创建表,程序关闭时,表进行删除
必须执行factory.close()才能删除
update:如果表不存在则创建,如果表存在,先回检查*.hbm.xml文件是否和表匹配,
如果不匹配将更新表结构(只添加,不删除)
validate:加载cfg.xml进效验,映射文件和数据表是否匹配,如果匹配正常操作,如果不匹配则抛出异常
### 显示的开发中先有的表,再有的映射文件
* 表 由DBA创建
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/tools/tb_books.hbm.xml"/>
</session-factory>
</hibernate-configuration>
上面代码,具体的含义不介绍了,网上太多了,只是介绍下mapping resource这个标签下的xxx.hbm.xml这个配置文件配置问题,直接显示该文件的全部路径com/tools/tb_books.hbm.xml
tb_books.hbm.xml配置文件相关代码(以下配置文件相关标签属性含义不多介绍,自己查):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.book.web3">
<class name="Book" table="tb_books">
<id name="id" column="id" type="int" >
<generator class="assigned" /> <!--generator这个坑,如果指定class为native会导致外部程序设置的主键id无效,且根据数据库自行判断采用自增长式 -->
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="price" type="double" column="price"></property>
<property name="bookCount" type="int" column="bookCount"></property>
<property name="author" type="string" column="author"></property>
</class>
</hibernate-mapping>
以上基本配置相关结束。
下面详细介绍hibernate使用
Book类如下:所有属性名称必须和数据库中的tb_books表属性名称一致,也必须和tb_books.hbm.xml配置文件property name,column一致。
package com.book.web3;
public class Book {
public static int PAGE_SIZE = 2;
private int id;
private String name;
private double price;
private int bookCount;
private String author;
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public double getPrice(){
return price;
}
public void setPrice(double price){
this.price = price;
}
public int getBookCount(){
return bookCount;
}
public void setBookCount(int bookCount){
this.bookCount = bookCount;
}
public String getAuthor(){
return author;
}
public void setAuthor(String author){
this.author = author;
}
}
创建hibernate初始化类:
package com.tools;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static SessionFactory sessionFactory = null;
static{
try {
Configuration cfg = new Configuration().configure("/hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err.println("创建会话工厂失败 err: " + e.toString());
e.printStackTrace();
}
}
public static Session getSession() throws HibernateException{
Session session = threadLocal.get();
if(session == null || !session.isOpen()){
if(sessionFactory == null){
rebuildSessionFactory();
}
session = (sessionFactory != null)?sessionFactory.openSession():null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory(){
try {
Configuration cfg = new Configuration().configure("/hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err.println("创建会话工厂失败 err: " + e.toString());
e.printStackTrace();
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static void closeSession()throws HibernateException{
Session session = threadLocal.get();
threadLocal.set(null);
if(session != null){
session.close();
}
}
}
创建hibernate java测试类,介绍了添加,查询,删除,修改数据库数据等
package com.book.web3;
import org.hibernate.Session;
import com.tools.HibernateUtil;
public class HibernateTest {
public HibernateTest() {
System.out.println("constructor");
}
public static void main(String[] args) {
// addData();
// queryData();
// deleteData();
modifyData();
}
private static void modifyData(){
Session session = null;
try {
session = HibernateUtil.getSession();
Book book = session.get(Book.class, new Integer("1005"));
book.setName("Java Web编程词典");
book.setAuthor("明日科技出品");
session.flush();
} catch (Exception e) {
System.out.print("对象修改失败");
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
private static void deleteData(){
Session session = null;
try {
session = HibernateUtil.getSession();
Book book = session.get(Book.class, new Integer("1006"));
session.delete(book);
session.flush();
} catch (Exception e) {
System.out.print("数据库删除失败");
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
private static void queryData(){
Session session = null;
try {
session = HibernateUtil.getSession();
Book book = session.get(Book.class, new Integer("1006"));
System.out.print("产品ID:" + book.getId());
System.out.print("产品名称:" + book.getName());
System.out.print("产品价格:" + book.getPrice());
System.out.print("产品数量:" + book.getBookCount());
System.out.print("作者:" + book.getAuthor());
} catch (Exception e) {
System.out.print("数据库查询失败");
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
private void addData(){
Session session = null;
Book book = new Book();
book.setId(10);
book.setName("深圳地理");
book.setPrice(50.0);
book.setBookCount(100);
book.setAuthor("北京出版社");
try {
session = HibernateUtil.getSession();
session.beginTransaction();
session.save(book);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
System.out.print("数据库添加失败");
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
}
可用命令查看相关修改结果
期间遇到一个问题, java.lang.UnsupportedClassVersionError: org/hibernate/cfg/Configuration : Unsupported major.minor version 52.0这个是由于刚开始用的hibernate版本是5.2.12的,重新下载一个5.1.0的换掉hibernate这一个jar就可以了
三:hibernate5二级缓存问题
1:在hibernate.cfg.xml配置文件中添加如下配置
<!-- 配置二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
以上标红部分需要注意,确定下载的ehcache的jar包里面存在EhCacheRegionFactory类,网上有一些其他的配置与ehcache版本有关,用的是hibernate-release-5.2.12.Final这个文件夹下的ehcache文件夹下的所有文件全部复制到
javaweb项目下的web-inf下的lib目录下,设置构建路径ok
注意property和mapping插入顺序不能错开,如果将property放在mapping标签后面会有如下错误提示:
配置
hibernate.cfg.xml
时提示
The content of element type “session-factory” must match “(property*,mapping*,(class-cache| collection-cache),event,listener*)”.
的错。
提示先配置property*元素,再配置mapping*元素,依次类推,仔细检查下看看你的程序中是否存在配置顺序错乱的情况。
只是因为在
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
之间存在元素配置顺序的错误,只需要按提示将顺序调整正确即可。
2:在hibernate.cfg.xml配置文件中指定二级缓存类,当然也可以在xxx.hbm.xml文件中指定,区别就不多说了,本文是在hibernate.cfg.xml配置文件中指定的
3:添加ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
<cache name="com.book.web3.Book"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/>
</ehcache>
该文件的路径如图所示,直接放在src根目录下
以上配置文件基本完成,运行最初介绍的java类,在入口函数添加twocache函数测试
public static void main(String[] args) {
// addData();
// queryData();
// deleteData();
// modifyData();
twoCahce();
}
private static void twoCahce(){
Session session = null;
Session session2 = null;
try {
session = HibernateUtil.getSession();
session2 = HibernateUtil.getSession();
Book book = session.get(Book.class, new Integer("1005"));
System.out.print("第一个session装载对象");
Book book2 = session.get(Book.class, new Integer("1005"));
System.out.print("第二个session装载对象");
} catch (Exception e) {
e.printStackTrace();
}finally{
HibernateUtil.closeSession();
}
}
发现有如下提示
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
Exception in thread "main" java.util.ServiceConfigurationError: org.hibernate.boot.registry.selector.StrategyRegistrationProvider: Provider org.hibernate.cache.ehcache.StrategyRegistrationProviderImpl not found
at java.util.ServiceLoader.fail(ServiceLoader.java:231)
at java.util.ServiceLoader.access$300(ServiceLoader.java:181)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:365)
at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.loadJavaServices(ClassLoaderServiceImpl.java:340)
at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.buildSelector(StrategySelectorBuilder.java:162)
at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:222)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:119)
at com.tools.HibernateUtil.<clinit>(HibernateUtil.java:12)
at com.book.web3.HibernateTest.queryData(HibernateTest.java:77)
at com.book.web3.HibernateTest.main(HibernateTest.java:14)
看上面的提示的意识是Provider org.hibernate.cache.ehcache.StrategyRegistrationProviderImpl not found,但是我们通过hibernate-ehcache-5.2.12.Final.jar包能够找到这个类,我也是找了好多资料都没找到答案,后来灵机一动会不会也是由于本本过高的原因
果然如此,将已经下载的hibernate-release-5.1.0.Final版本文件里面的ehcache里面的hibernate-ehcache-5.1.0.Final.jar代替lib下的hibernate-ehcache-5.2.12.Final.jar,就ok啦
运行结果
以上关于hibernate配置问题以及二级缓存相关问题就结束了,自学还是可以学到很多东西