Spring2.5 + Hibernate 的annotation配置

Struts2、Spring2.5和Hibernate3.2是现在最常用的轻量级JavaEE配套解决方案。几个月的使用后我感觉到Spring传统的xml配置方式配置文件庞大,跟踪很费力。Spring2.5提供了基于annotation的配置。使用annotation配置后,不需要每个bean都写到xml中,只需要在类声明前加一个@Component或者@Service就好了,事务控制更是简单,一个@Transactional就好。配置清爽了,后来的小家伙们也容易读了。

Hibernate方面使用xml配置时经常会遇到实体类添加了新属性,而配置文件没有同步修改带来的问题。改用annotation配置一方面解决了容易遗漏对配置文件的修改的问题,同时也减少了配置文件的体积。参考了reference和若干网文后,我总结了如下简洁的配置策略。

spring的配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"

	xmlns:tx="http://www.springframework.org/schema/tx"

	xsi:schemaLocation="

    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:annotation-config />

	<context:component-scan base-package="quickstart" />

	<bean id="sessionFactory"

		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

		<property name="configLocation" value="classpath:/hibernate.cfg.xml" />

	</bean>

	<bean id="transactionManager"

		class="org.springframework.orm.hibernate3.HibernateTransactionManager">

		<property name="sessionFactory" ref="sessionFactory" />

	</bean>

	<tx:annotation-driven transaction-manager="transactionManager" />

</beans>

这里我采用了Hibernate配置文件独立存放的策略,对这两份不相关领域的文件单独维护。Hibernate配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

	    <property name="connection.datasource">java:/comp/env/jdbc/QuickstartDB</property>

        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <mapping class="quickstart.model.Person"/>

    </session-factory>

</hibernate-configuration>

这里采用了服务器通过JNDI提供的数据源,而不是很多人喜欢的Spring提供数据源,后面再做解释。另外,这里需要将实体类一一列出,Hibernate annotation不支持自动搜索标注实体类,试过,<mapping package="..."/>不是干这个用的。

下面对方案选择进行一下解释:

  1. 使用Hibernate annotation而不是JPA(Hibernate EntityManager),是因为JPA的API还没有Hibernate的好用,在处理分页的时候Criteria比Query简洁多了。关于分页,另起帖子说。

  2. 使用服务器通过JNDI提供的数据源而非Spring数据源,是因为服务器上配置数据源很灵活,如果使用Spring的数据源,就相当于把数据库的地址写死在程序里了。应用部署到客户那里,他们一旦有类似修改服务器IP地址的操作,就需要修改数据源的配置。这时如果配置在spring的xml文件中就麻烦了。而目前常用的servlet服务器都提供可视化的数据源配置界面,操作起来很容易。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值