Spring和Hibernate:我可以摆脱hibernate.cfg.xml并单独依赖注释吗?

时间:2011-11-10 05:08:37

标签: hibernate spring

我一起使用spring和hibernate。在我的应用程序上下文中,我有这一部分:

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration
            </value>
        </property>

hibernate.cfg.xml只包含我们希望hibernate管理持久性的类列表。

我想知道我是否可以完全替换这个文件?我们可以单独依靠注释来发现需要ORM的类列表吗?

如果春天可以,那怎么样?

1 个答案:

答案 0 :(得分:10)

AnnotationSessionFactoryBean

例如

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="namingStrategy">
        <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
    </property>
    <property name="hibernateProperties">
        <props>
            <!-- Hibernate configurations -->
            <prop key="hibernate.dialect"><!-- dialect --></prop>
            <prop key="hibernate.cache.use_second_level_cache"><!-- use_second_level_cache --></prop>
            <!-- and so on -->
        </props>
    </property>

    <!-- Package to scan for entity classes -->
    <property name="packagesToScan" value="com.domain" />

    <!-- OR -->
    <property name="packagesToScan">
        <list>
            <value>com.domain1</value>
            <value>com.domain2</value>
        </list>
    </property>

    <!-- OR -->     
    <property name="annotatedClasses">
        <list>
            <value>com.domain.Entity1</value>
            <value>com.domain.Entity2</value>
        </list>
    </property>
</bean>