我目前使用Spring 3.1&amp; amp ;;扫描DAO和服务包。 Hibernate 4通过<context:component-scan>
是否有办法对标记为@Entity
的类执行相同操作,而不是使用configLocation
属性和hbm.xml
文件?
<hibernate-configuration>
<session-factory>
<mapping class="com.example.model.User" />
<!-- etc. -->
</session-factory>
</hibernate-configuration>
答案 0 :(得分:37)
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="WEB-INF/classes/hibernate.cfg.xml"
p:packagesToScan="com.example.model"
/>
将扫描模型包中的所有内容。我使用cfg.xml包含show_sql和hb2ddl.auto等设置。
答案 1 :(得分:19)
您可以在应用程序context.xml文件中执行此类操作来扫描所有注释类 -
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="lobHandler" ref="lobHandler"/>
<property name="packagesToScan">
<list>
<value>com.idc.scd.domain</value>
<value>com.idc.scd.domain.dropdown</value>
<value>com.idc.scd.domain.external</value>
<value>com.idc.scd.domain.pk</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
<prop key="hbm2ddl.auto">validate</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.connection.release_mode">after_statement</prop>
<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
<prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
</props>
</property>
</bean>
答案 2 :(得分:3)
您可以使用Spring的mappingLocations属性指定spring查找hibernate映射文件的位置。
<property name="mappingLocations" value="classpath:com/example/model/hibernate/*.hbm.xml"/>
希望这有帮助。
答案 3 :(得分:3)
简化,你可以在配置文件'spring-servlet.xml'中使用如下代码:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.your.bean.package" />
</bean>
注意: