编者注
之前在编写HavaWeb的框架的时候,就碰到这个问题了。但是由于懒,没有处理。最近拿起框架继续处理。在单元测试的时候,确实报出该问题。随即详细检查。
问题描述
在一个典型的单元测试用例中,在启动Tomcat后正式运行,没有发生任何问题。能够正常save数据内容,Spring也没有报错。但是在单元测试之中却发生了错误java.lang.IllegalArgumentException: Not a managed type: class xxx.entity.Entity
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("/src/main/webapp")
@ContextConfiguration(locations = {
"classpath:appconfig/mvc/spring/servlet-context.xml"
})
public class EntityJPAServiceTest {
@Autowired
EntityJPAService entityJPAService;
@Test
public void getInsert() throws Exception {
Entity entity= new Entity();
entity.setName("entity01");
entity.setDescription(entity.getName() + " Decription");
entity.setSpaceType(SpaceType.interior);
entity.setTitle("Entity01");
entityJPAService.create(entity);
}
}
经过确实的查询和附录的链接提供的信息发现是配置文件的错误
<!-- 对JPA声明以hibernate进行实现 -->
<!-- hibernate 5.2.x after -->
<bean id="persistenceProvider" class="org.hibernate.jpa.HibernatePersistenceProvider"/>
<!-- hibernate 5.1.x before -->
<!--<bean id="persistenceProvider" class="org.hibernate.ejb.HibernatePersistence"/>-->
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
<!-- JPA进行实体扫描 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 自动扫描Entity实体 -->
<property name="packagesToScan" value="org.aicfve"/>
<!-- 指明JPA的persistence的配置文件位置 -->
<!-- 注意:如果使用在springmvc做配置,则不要引用persistence.xml,否则单元测试发生错误 -->
<property name="persistenceXmlLocation" value="classpath:appconfig/orm/jpa/persistence.xml" />
<property name="persistenceUnitName" value="persistenceUnit"/>
<!-- 注入dataSource -->
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<!-- 指定具体实现ORM框架的特定属性 -->
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
</props>
</property>
</bean>
首先在persistence.xml中添加对应的class内容,能够正确解决该问题,但是随即带来的所有的Entity并不通过扫描,而是要手动输入,工作量太大。放弃了这种方法。
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<!-- hibernate 5.2.x after -->
<!--<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>-->
<!-- hibernate 5.1.x before -->
<!--<provider>org.hibernate.jpa.HibernatePersistence</provider>-->
<!--<properties>-->
<!--<property name="hibernate.ejb.cfgfile" value="classpath:appconfig/orm/hibernate/hibernate.cfg.xml" />-->
<!--</properties>-->
<class>xxx.entity.Entity</class>
</persistence-unit>
主要的发生问题是如下两句,这两句
<property name="persistenceXmlLocation" value="classpath:appconfig/orm/jpa/persistence.xml" />
<property name="persistenceUnitName" value="persistenceUnit"/>
解决方法
上面两句话都删除,或者删除任意一条,都可以解决这个问题。在正式运行与单元测试,不会发生问题。
附录
不在JPA 的 persistence.xml 文件中配置Entity class的解决办法