spring自动扫描实体配置

来源:互联网 发布:空闲电脑 云计算 赚钱 编辑:程序博客网 时间:2024/04/26 03:29

先看配置代码:

<p:bean id="sessionFactory"

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<p:property name="dataSource" ref="datasource" />
<p:property name="packagesToScan" value="com.example.entity.*" /> 
<!--<p:property name="configLocations">
<p:value>/WEB-INF/conf/hibernate.cfg.xml</p:value>
</p:property>-->

</p:bean>

代码注释掉的部分是通过hibernate.cfg.xml文件来描述实体的映射关系的,这种方式需要写出类的目录。文件的格式入下:

<?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>         
<mapping class="com.example.entity.Entity1"/>
<mapping class="com.example.entity.Entity2"/>
<mapping class="com.example.entity.Entity3"/>
<mapping class="com.example.entity.Entity4"/>
     </session-factory>
</hibernate-configuration>

而注释上方的property也可以达到相似的目的,只需要将value的值改为自己的实体目录,这个目录有两个方式,

1、直接填完整包名,spring扫描该目录下的实体;

2、上一级完整包名.*扫描目录下再下一级的实体,适合实体在多个目录下。例如,com.example.*,他会匹配的路径是:com.example.base.Entity1也可以是com.example.pre.Entity2,但是不可以是com.example.Entity3.

0 0
原创粉丝点击