码迷,mamicode.com
首页 > 编程语言 > 详细

Spring和Hibernate相遇

时间:2015-08-09 13:58:30      阅读:537      评论:0      收藏:0      [点我收藏+]

标签:

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相遇

标签:

原文地址:http://www.cnblogs.com/xiashiwendao/p/4715026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!