Spring和Hibernate相遇
Spring是一个很贪婪的家伙,看到他的长长的jar包列表就知道了,其实对于hibernate的所有配置都是可以放在Spring中来进行得,但是我还是坚持各自分明,Spring只是负责自动探测声明类(不用每次添加类都去到配置文件中进行配置,尤其团队作业还有文件冲突问题),Hibernate的配置文件专门负责和数据打交道;
Spring的最小jar子集:beans,context,core,expression;如何是和Hibernate合作,还需要添加orm以及tx(事务相关);Hibernate到了4就非常友好,直接将libs文件夹里面的requires里面的jar包放到里面就可以了(3的话还需要把根目录的Hibernate3.jar放入);
- ApplicationContext配置如下:
<?xml
version="1.0"
encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
"
default-autowire="byName"
default-lazy-init="false">
<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
<bean
id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property
name="configLocation"
value="classpath:hibernate.cfg.xml"
/>
<property
name="packagesToScan"
value="com.hbm.entity.*">
<!-- <list>
<value>com.historycreator.hibernate</value>
</list> -->
</property>
<!-- <property name="annotatedPackages">
<list>
<value>com.historycreator.hibernate</value>
</list>
</property>
<property name="annotatedClasses">
<list>
<value>com.historycreator.hibernate.Event</value>
<value> com.historycreator.hibernate.Log</value>
</list>
</property> -->
</bean>
</beans>
Xmlns以及xmlns:xsi以及xsi都是需要有的;如果只声明了xmlns:xsi,但是没有描述xsi将会报错;这里我认为推测应该是spring在加载的时候是会读取这些值,然后对xml文件进行校验;因为如果将xmlns写错或者不写都将会在运行时出错;所以对于命名空间以及xsd文件的描述是必须的;
校验xml文件格式,首先会根据命名空间到spring-context的jar下面的WEB-INF中找到spring.schemas,到schemas下面找到对应的文件(xsd文件,一般都是放置在"org/springframework/*/config/"下面);如果本地找不到,他将会到网上下载xsd文件对xml的schema进行校验;
对于sessionFactory的bean的描述,对于Hibernate3来说是" org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean",但是对于Hibernate4而言是" org.springframework.orm.hibernate4.LocalSessionFactoryBean",你会发现在Spring4里面是找不到针对H4的AnnotationSessionFactoryBean(只是在H3的support包下面有这个bean),已经全盘的放置到了LocalSessionFactory中,在里面会找到setAnnotatedPackages以及setAnnotatedClasses方法(这些方法在H3下面的LocalSessionFactory是没有的),这些都是在H3-supportjar包下面的AnnotationSessionFactory下面可以找到;所以LocalSessionFactory已经全面取代了H3时代的AnnotationSessionFactory;
为了实现监听统配,见"packagesToScan",value采用的是统配的方式,所有包体名称符合的包下面的类都将会被监听,这样就不需要每次添加entity都到配置文件中注册;"packagesToScan"还有一种描述方式就是通过填充<list>节点的方式,这种方式只能是声明完整地包名称,不能使用通配模式;
与之类似的是annotatedPackage,这个property基本可以忽略,没什么卵用,需要添加在包体中添加package-info文件,然后进行anntation才可以;
annotedClasses可以通过配置value以及<list>方式进行指定,但是必须是完整路径,无法使用通配模式;
- 入口类:
public
class EventManager {
static ApplicationContext ctx;
static {
ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
}
public
static ApplicationContext getContext(){
return
ctx;
}
… …
}
对于Spring的应用程序(Web程序启动的时候会自动加载,配置文件ApplicationContext.xml路径在放置在WEB-INF下面),需要在启动的时候手动进行容器配置文件初始化,见红色部分;
- 在Hibernate初始化:
public
class HibernateUtil {
private
static
final SessionFactory sessionFactory = buildSessionFactory();
private
static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
//return new Configuration().configure().buildSessionFactory();
return (SessionFactory)EventManager.getContext().getBean("sessionFactory");
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw
new ExceptionInInitializerError(ex);
}
}
public
static SessionFactory getSessionFactory() {
return
sessionFactory;
}
}
- 使用Hibernate进行数据库操作:
public
class EventManager {
… …
public
static
void main(String[] args) {
EventManager mgr = new EventManager();
mgr.createAndStoreEvent("My Event", new Date());
mgr.showEvents();
HibernateUtil.getSessionFactory().close();
System.out.println("OK, Complete!");
}
private
void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
Log theLog = new Log();
theLog.setLogInfo("well, well, OK!");
session.save(theLog);
session.getTransaction().commit();
}
private
void
showEvents() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List
result = session.createQuery("from Event").list();
for (Event event : (List<Event>) result) {
System.out.println("Event Title: " + event.getTitle());
}
session.getTransaction().commit();
}
}
Spring和Hibernate相遇的更多相关文章
- 【译】Spring 4 + Hibernate 4 + Mysql + Maven集成例子(注解 + XML)
前言 译文链接:http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annot ...
- 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】
一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...
- spring和Hibernate整合
首先导入spring和Hibernate的jar包,以及JDBC和c3p0的jar包, 然后就是Hibernate的XML配置文件,不需要加入映射文件,这里用spring容器管理了. Hibernat ...
- 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)
轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...
- spring整合hibernate的详细步骤
Spring整合hibernate需要整合些什么? 由IOC容器来生成hibernate的sessionFactory. 让hibernate使用spring的声明式事务 整合步骤: 加入hibern ...
- spring整合hibernate
spring整合hibernate包括三部分:hibernate的配置.hibernate核心对象交给spring管理.事务由AOP控制 好处: 由java代码进行配置,摆脱硬编码,连接数据库等信息更 ...
- spring 整合hibernate
1. Spring 整合 Hibernate 整合什么 ? 1). 有 IOC 容器来管理 Hibernate 的 SessionFactory2). 让 Hibernate 使用上 Spring 的 ...
- 总结Spring、Hibernate、Struts2官网下载jar文件
一直以来只知道搭SSH需要jar文件,作为学习的目的,最好的做法是自己亲自动手去官网下.不过官网都是英文,没耐心一般很难找到下载入口,更何 况版本的变化也导致不同版本jar文件有些不一样,让新手很容易 ...
- spring和hibernate整合时无法自动建表
在使用spring整合hibernate时候代码如下: <property name="dataSource" ref="dataSource" /> ...
随机推荐
- 关于AFNetworking访问网络超时的设置
前言:有的猿会发现在设置AFNetworking访问网络超时时,直接用self.manager.requestSerializer.timeoutInterval =10.f不起作用. 解决办法:经过 ...
- iOS UIKit:TableView之编辑模式(3)
一般table view有编辑模式和正常模式,当table view进入编辑模式时,会在row的左边显示编辑和重排控件,如图 42所示的编辑模式时的控件布局:左边的editing control有表 ...
- 页面常见效果js实现
2015.12.2 页面常见效果js实现 [有没有觉得很坑,[笑哭,邮箱写上]] 复习: Js内置对象: 1.浏览器对象 window document history location event ...
- js购物时的放大镜效果
首先需要两张一样的图片,一张大图,一张小图,大图显示,当鼠标移入时,小图上出现一个滑块,可以滑动,大图也跟着显示,大图的显示区域和小图一样,当滑块滑到不同的位置,大图显示不同的区域,当鼠标移出时,滑块 ...
- 学会用Reflector调试我们的MVC框架代码
我们知道,现在能调试.net程序通常有两个,第一个是ILSpy,还是一个是Reflector,这两个小反编译软件算是我们研究底层代码中所拥有的一把 锋利小尖刀~~~,比如你看到的ILSpy这样的界面图 ...
- static的用途
1)限制变量的作用域:即在函数体,一个被声明为静态的变量在这一函数被调用过程中维持其值不变: 2)限制变量的存储域:<a>在模块内(但在函数体外),一个被声明为静态的变量,可以被模块内的所 ...
- 注释玩转webapi
using System; using System.Collections.Generic; using System.Net.Http.Formatting; using System.Web.H ...
- ibatis+spring+cxf+mysql搭建webservice
首先需必备:mysql.myeclipse6.5.apache-cxf-2.6.2 一.建数据库,库名:cxf_demo:表名:book CREATE DATABASE `cxf_demo` --数 ...
- C语言——N个人围成一圈报数淘汰问题
<一>问题描述: 有17个人围成一圈(编号为0-16),从第 0号的人开始从 1报数, 凡报到 3的倍数的人离开圈子,然后再数下去,直到最后只剩下一个人为止. 问此人原来的位置是多少号? ...
- zoj 1649 Rescue (BFS)(转载)
又是类似骑士拯救公主,不过这个是朋友拯救天使的故事... 不同的是,天使有多个朋友,而骑士一般单枪匹马比较帅~ 求到达天使的最短时间,杀死一个护卫1 units time , 走一个格子 1 unit ...