Spring是一个很贪婪的家伙,看到他的长长的jar包列表就知道了,其实对于hibernate的所有配置都是可以放在Spring中来进行得,但是我还是坚持各自分明,Spring只是负责自动探测声明类(不用每次添加类都去到配置文件中进行配置,尤其团队作业还有文件冲突问题),Hibernate的配置文件专门负责和数据打交道;

Spring的最小jar子集:beans,context,core,expression;如何是和Hibernate合作,还需要添加orm以及tx(事务相关);Hibernate到了4就非常友好,直接将libs文件夹里面的requires里面的jar包放到里面就可以了(3的话还需要把根目录的Hibernate3.jar放入);

 

  1. 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>方式进行指定,但是必须是完整路径,无法使用通配模式;

  1. 入口类:

public
class EventManager {

    static ApplicationContext ctx;

    static {

        ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");

    }

 

    public
static ApplicationContext getContext(){

        return
ctx;

    }

 

    … …

}

对于Spring的应用程序(Web程序启动的时候会自动加载,配置文件ApplicationContext.xml路径在放置在WEB-INF下面),需要在启动的时候手动进行容器配置文件初始化,见红色部分;

  1. 在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;

    }

 

}

  1. 使用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相遇的更多相关文章

  1. 【译】Spring 4 + Hibernate 4 + Mysql + Maven集成例子(注解 + XML)

    前言 译文链接:http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annot ...

  2. 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】

    一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...

  3. spring和Hibernate整合

    首先导入spring和Hibernate的jar包,以及JDBC和c3p0的jar包, 然后就是Hibernate的XML配置文件,不需要加入映射文件,这里用spring容器管理了. Hibernat ...

  4. 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)

    轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...

  5. spring整合hibernate的详细步骤

    Spring整合hibernate需要整合些什么? 由IOC容器来生成hibernate的sessionFactory. 让hibernate使用spring的声明式事务 整合步骤: 加入hibern ...

  6. spring整合hibernate

    spring整合hibernate包括三部分:hibernate的配置.hibernate核心对象交给spring管理.事务由AOP控制 好处: 由java代码进行配置,摆脱硬编码,连接数据库等信息更 ...

  7. spring 整合hibernate

    1. Spring 整合 Hibernate 整合什么 ? 1). 有 IOC 容器来管理 Hibernate 的 SessionFactory2). 让 Hibernate 使用上 Spring 的 ...

  8. 总结Spring、Hibernate、Struts2官网下载jar文件

    一直以来只知道搭SSH需要jar文件,作为学习的目的,最好的做法是自己亲自动手去官网下.不过官网都是英文,没耐心一般很难找到下载入口,更何 况版本的变化也导致不同版本jar文件有些不一样,让新手很容易 ...

  9. spring和hibernate整合时无法自动建表

    在使用spring整合hibernate时候代码如下: <property name="dataSource" ref="dataSource" /> ...

随机推荐

  1. [GIF] Colors in GIF Loop Coder

    In this lesson we cover the different methods for defining and animating colors in GIF Loop Coder. f ...

  2. android88 录音机

    package com.itheima.recorder; import android.os.Bundle; import android.app.Activity; import android. ...

  3. count(1) count(*)

    mysql from t; +---+ | +---+ | | | | +---+ rows in set (0.00 sec) mysql) from t; +----------+ ) | +-- ...

  4. linux find命令详解--转

    转自:http://blog.csdn.net/jakee304/article/details/1792830 (一)Get Start 最简单的find用法莫过于如此: $ find . 查找当前 ...

  5. 玩转Android之数据库框架greenDAO3.0使用指南

    用过ActiveAndroid.玩过ORMLite,穿过千山万水,最终还是发现greenDAO好用,ActiveAndroid我之前有一篇文章介绍过 玩转Android之数据库框架ActiveAndr ...

  6. android夸项目调用

    将工程A做成android library project. 设置工程A,右键->Properties->Android,将Is library项选中,然后Apply.设置工程B,右键-& ...

  7. C# 解决DrawImage绘制图片拉伸产生渐变

    ImageAttributes ImgAtt = new ImageAttributes(); ;                 ImgAtt.SetWrapMode(System.Drawing. ...

  8. nyoj 32 组合数

    组合数 时间限制:3000 ms  |            内存限制:65535 KB 难度:3   描述 找出从自然数1.2.... .n(0<n<10)中任取r(0<r< ...

  9. Mac 下显示隐藏文件

    将下面的命令粘贴进终端,按提示操作即可(可能需要输入电脑密码) 显示:defaults write com.apple.finder AppleShowAllFiles -bool true 隐藏:d ...

  10. xcode插件安装完之后无法使用问题解决

    1.打开xcode插件所在的目录: 例如: ~/wangdi/library/Application Support/Developer/Shared/Xcode/Plug-ins /Users/su ...