1.概述
值得期待的Hibernate Annotation 式配置终于随着Hibernate 3.2GA 版本的发布而宣布正式被支持了!
只要数据库以及字段名称设计合适,我们甚至只需要在原来程序上加上3行代码,就可以配置完成一个Bean。这依 稀看到了Rails 的影子......
1.1 参考资料
最为重要的参考资料莫过于由RedSega 团队翻译的,并入Hibernate 官方文档库的参考手册中文版。
2.系统配置
1. 首先,需要将hibernate-annotations 的相关jar 包(hibernate-annotations.jar,hibernate-commons- annotations.jar,ejb3-persistence.jar)引入项目。
2. 可以使用hibernate.cfg.xml ,也可以使用Spring的封装来配置annotation pojo
a. 直接在spring中配置 sessionFactory的类型改为 org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
增加如下节点配置
<property name="annotatedClasses">
<list><value>org.springside.helloworld.model.User</value></list>
</property>
b. 在hibernate.cfg.xml 中配置
创建hibernate.cfg.xml 文件,以SpringSide 项目的HelloWorld 为例,写入以下内容
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">
<hibernate-configuration>
<session-factory>
<mapping class="org.springside.helloworld.model.User"/>
</session-factory>
</hibernate-configuration>
同时,在Spring 配置文件中,将原来的SessionFactory 配置改为:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocations">
<list><value>classpath*:/config/hibernate.cfg.xml</value></list>
</property>
<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>
</bean>