在Spring 集成 Hibernate 的JPA方式中,需要在persistence配置文件中定义每一个实体类,这样非常地不方便,远哥目前找到了2种方法。
这2种方式都可以实现不用persistence.xml文件,免去每个Entity都要在
persistence.xml
文件中配置的烦恼,但是这种方式
Entity实体类的主键字段注解@ID要放到 getXXX()方法上,否则不认。
方式1:
修改“LocalContainerEntityManagerFactoryBean”的配置,如下:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="com.pilicat.data.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.connection.driver_class">${jdbc.driverClassName}</prop>
<prop key="hibernate.connection.url">${jdbc.url}</prop>
<prop key="hibernate.connection.username">${jdbc.username}</prop>
<prop key="hibernate.connection.password">${jdbc.password}</prop>
<prop key="hibernate.c3p0.min_size">10</prop>
<prop key="hibernate.hbm2ddl.auto">true</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
方式2:
修改“LocalContainerEntityManagerFactoryBean”的配置,如下:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceXmlLocation" value="classpath:persistence-app.xml" />
<!--
<property name="persistenceUnitName" value="com.pilicat.data.entity" /> -->
<property name="packagesToScan" value="com.pilicat.data.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${hibernate.dialect}" />
<property name="generateDdl" value="true" />
</bean>
</property>
</bean>
去掉“
persistenceUnitName
”属性,添加“
packagesToScan
”属性,但是
persistence.xml配置文件中的persistence-unit名字照样保留。