Spring JPA - 至少需要一个JPA元模型的存在*

6
有人知道为什么它不起作用吗?
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
06/04/2017 14:11:24.732 ERROR [main] - org.springframework.boot.SpringApplication: Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
    at com.cadit.web.WebApplicationAware.main(WebApplicationAware.java:19)
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
    at org.springframework.util.Assert.notEmpty(Assert.java:277)
    at org.springframework.data.jpa.mapping.JpaMetamodelMappingContext.<init>(JpaMetamodelMappingContext.java:52)
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:71)
    at org.springframework.data.jpa.repository.config.JpaMetamodelMappingContextFactoryBean.createInstance(JpaMetamodelMappingContextFactoryBean.java:26)
    at org.springframework.beans.factory.config.AbstractFactoryBean.afterPropertiesSet(AbstractFactoryBean.java:134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 16 common frames omitted

我在com.cadit.entities中定义了实体:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TEST")
public class GenericBeans implements BeanType, IEntity<Long> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "TEST_PAID")
    protected Long id;

    @Column(name = "SOCIETA")
    private String SocietaCod;
    @Column(name = "CONTO_INTERMEDIARIO")
    private String contoInt;
    @Column(name = "TIPO_OPERAZIONE")
    private String tipoOpe;


    public GenericBeans(String societaCod, String contoInt, String tipoOpe) {
        SocietaCod = societaCod;
        this.contoInt = contoInt;
        this.tipoOpe = tipoOpe;
    }


    public GenericBeans() {

    }




    public String getSocietaCod() {
        return SocietaCod;
    }


    public void setSocietaCod(String societaCod) {
        SocietaCod = societaCod;
    }


    public String getContoInt() {
        return contoInt;
    }


    public void setContoInt(String contoInt) {
        this.contoInt = contoInt;
    }


    public String getTipoOpe() {
        return tipoOpe;
    }


    public void setTipoOpe(String tipoOpe) {
        this.tipoOpe = tipoOpe;
    }


    @Override
    public String toString() {
        return "CSV [SocietaCod=" + SocietaCod + ", contoInt=" + contoInt + ", tipoOpe=" + tipoOpe + "]";
    }


    @Override
    public Long getId() {
        return this.id;
    }


    @Override
    public void setId(Long id) {
        this.id=id;     
    }

}

我为Spring定义了datasource数据源入口的定义:

import org.apache.log4j.Logger;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@ComponentScan
@EntityScan("com.cadit.entities")
//@EnableJpaRepositories("com.cadit.entities")
@EnableTransactionManagement
@PropertySource("classpath:db-config.properties")
public class DbAutoConfiguration {


     static final Logger logger = Logger.getLogger(DbAutoConfiguration.class);

    public DbAutoConfiguration() {

    }


    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource(){
        //DataSource ds =new EmbeddedDatabaseBuilder().addScript("classpath:sql/schema.sql").addScript("classpath:testdb/data.sql").build();
        DataSourceBuilder ds =  DataSourceBuilder.create();
        logger.info("dataSource = " + ds);
        return ds.build();

    }
}

我的db-config.properties文件如下:

spring.jpa.hibernate.ddl-auto: validate
spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.database: SQL
spring.jpa.show-sql: true

spring.datasource.driverClassName=net.sourceforge.jtds.jdbc.Driver
spring.datasource.url=jdbc:jtds:sqlserver://localhost:1433;databaseName=example
spring.datasource.username=xxx
spring.datasource.password=xxx

IEntity是:

public interface IEntity <I extends Serializable> extends Serializable{

/**
  * Property rappresenta la primary key.
  */
  String P_ID = "id";

  /**
   * restituisce la primary key
   * @return
   */
  I getId();

  /**
   * imposta la primary key
   * @param id
   */
  void setId(I id);
}

我尝试使用Spring的CrudRepository接口将CSV文件写入数据库:

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.repository.CrudRepository;

import com.cadit.entities.GenericBeans;
import com.csvreader.CsvReader;

public class CsvReaders {

    static final Logger logger = Logger.getLogger(CsvReader.class);

    @Autowired
    public CrudRepository<GenericBeans,Long> _entitymanager;

    public List loadDataFromCsv(String fileName) {
        try {

            File file = new ClassPathResource(fileName).getFile();
            CsvReader csv = new CsvReader(file.getAbsoluteFile().getPath(),';');
            csv.readHeaders();
            List l = new LinkedList();
            GenericBeans b = new GenericBeans ();
            while (csv.readRecord())
            {
                b.setSocietaCod(csv.get(0));
                b.setContoInt(csv.get(1));
                b.setTipoOpe(csv.get(2));
                _entitymanager.save(b); //persist on db
                l.add(b);
                b = new GenericBeans();
            }
            b=null;
            return l;
        } catch (Exception e) {
            logger.error("Error occurred while loading object list from file " + fileName, e);
            return Collections.emptyList();
        }
    }


} 

我没有使用main类,而是使用一个继承了SpringBootServletInitializer的类,因为我希望在独立的Tomcat和Tomcat安装作为WAR应用程序上运行它。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan(basePackages={"com.cadit.entities","com.cadit.beans"})
@EnableAutoConfiguration
public class WebApplicationAware extends SpringBootServletInitializer {

    private static Class<WebApplicationAware> applicationClass = WebApplicationAware.class;

      public static void main(String[] args) {
            SpringApplication.run(applicationClass, args);
        }

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(applicationClass);
        }




}

所有的属性文件都在类路径资源中,因为这是一个Maven项目。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>xxxx</artifactId>
    <version>0.1.0</version>
    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId> 
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
       <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.11.1.RELEASE</version>
    </dependency>
    <dependency> 
        <groupId>javax.persistence</groupId> 
        <artifactId>persistence-api</artifactId> 
        <version>1.0.2</version> 
    </dependency> 


        <!-- altre dipendenze non spring -->
        <!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
        <dependency>
            <groupId>net.sourceforge.javacsv</groupId>
            <artifactId>javacsv</artifactId>
            <version>2.0</version>
        </dependency>

        <!--  per jpa solo se si usa il Tomcat embedded -->
        <dependency>
            <groupId>net.sourceforge.jtds</groupId>
            <artifactId>jtds</artifactId>
            <version>1.3.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <!--  end -->


         <!-- dipendenze logback -->
      <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.5</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.7</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.7</version>
        </dependency>

        <!-- fine dip logback -->

    </dependencies>

    <properties>
     <start-class>hello.WebApplicationAware</start-class>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>


    <build>

   <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

运行WebApplicationAware类时,为什么无法找到JPA实体?这是什么问题?
3个回答

11

Spring没有找到任何JPA实体,因此没有创建任何JPA元模型,这就是你遇到异常的原因。

问题的原因可能是您类路径上的持久性api版本不正确。

您正在使用

<dependency> 
    <groupId>javax.persistence</groupId> 
    <artifactId>persistence-api</artifactId> 
    <version>1.0.2</version> 
</dependency> 

但我相当确定你的Spring版本使用了persistence-api版本2。

你是否在使用来自版本1的@Entity注释?在运行时,Spring将使用版本2,并且这将仅搜索使用版本2的@Entity!

移除这些依赖。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>    
<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>1.11.1.RELEASE</version>
</dependency>

改为添加

  <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

这将为您提供所有正确版本的JPA依赖项。


我更改了org.hibernate.javax.persistence中的持久性 -> hibernate-jpa-2.1-api,并应用于DbAutoConfiguration.class上的规则,网址为https://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html(77.6使用自定义EntityManagerFactory和77.7使用两个EntityManagerFactory),我在同一类中添加了PlatformTransactionManager和注释@EnableJpaRepositories(entityManagerFactoryRef = " DbEntityManagerFactory",transactionManagerRef = "DbTransactionManager")。我添加了hibernate-core和aspectjweaver的pom依赖项,并且未更改spring-data-jpa版本。 - robyp7

3

我通过添加两个注释解决了这个问题。

@EnableAutoConfiguration
@EntityScan(basePackages = { "com.wt.rds" })

我的依赖关系在Gradle中

compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.4.RELEASE'

0

不幸的是,大多数关于JPA集成测试的Spring Boot指南都会在这里或那里缺少一些配置。

所以这里给出一个例子,希望能对你有所帮助。

第一点。 我的本地环境目前设置为使用Spring Boot版本:

<version.spring.boot>1.5.9.RELEASE</version.spring.boot>

话虽如此,我目前正在设置我的本地环境,以便能够针对多个数据库运行集成测试(例如postgres、hsql、h2)。 因此,我首先通过谷歌搜索任何一个解决这个问题的随机教程。

下一个链接就是其中一个例子:

https://www.baeldung.com/spring-testing-separate-data-source

以上示例是一个很好的起点。它允许您获取有效的实体和有效的存储库。另一方面,springboot测试类本身还有很多需要改进的地方。
通过上述示例,您将立即遇到集成测试的问题。您会发现示例没有提供application.class来配置集成测试,而且您不知道需要在哪里放置springboot注释才能使测试最终运行而不出错。
因此,现在我给您提供了一个最小的3个类(Entity + Repository + SpringbootTest),这些类应该具有您需要的100%的配置。这将作为您未来进行任何基于JPA的集成测试的基础,然后您可以交换实体和存储库,并继续使用相同类型的srpingboot配置进行测试。
我首先给您提供不相关的类。那些始终相同的东西,您想要测试的东西,与配置无关的东西。我指的是REPOSITORY + ENTITY。
在eclipse中创建您的java包: tutorial.www.baeldung.com.tutorial001jpa.separateDS
将以下简单的实体和存储库类转储到此包中,这些类基于我上面提供的教程参考。
Tutorial001GenericEntity

package tutorial.www.baeldung.com.tutorial001jpa.separateDS;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "TUTORIAL_001_GENERIC_ENTITY")
public class Tutorial001GenericEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String value;

    public Tutorial001GenericEntity() {
        super();
    }

    public Tutorial001GenericEntity(String value) {
        super();
        this.value = value;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    // standard constructors, getters, setters

}

然后我们来看第二个简单的代码片段。 Spring存储库样板代码。

Tutorial001GenericEntityRepository


package tutorial.www.baeldung.com.tutorial001jpa.separateDS;

import org.springframework.data.jpa.repository.JpaRepository;

public interface Tutorial001GenericEntityRepository extends JpaRepository<Tutorial001GenericEntity, Long> {

}

此时,您的Maven项目src/test/java共有两个类。基本的东西。 一个实体和一个存储库,它们作为您需要执行的任何集成测试的示例。

现在,您进入示例中唯一重要的类,这是始终会出现很多问题的内容,即SpringBoot测试类,它不仅负责测试业务逻辑,还具有配置测试的复杂任务。

在这种情况下,此测试类具有允许SpringBoot发现您的实体、存储库等所有注释。

package tutorial.www.baeldung.com.tutorial001jpa.separateDS;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
        tutorial.www.baeldung.com.tutorial001jpa.separateDS.Tutorial001GenericEntityIntegrationTest.ConfigureJpa.class })
@SpringBootTest()
public class Tutorial001GenericEntityIntegrationTest {

    @EntityScan(basePackageClasses = { Tutorial001GenericEntity.class })
    @EnableJpaRepositories(basePackageClasses = Tutorial001GenericEntity.class)
    @EnableAutoConfiguration()
    public static class ConfigureJpa {

    }

    @Autowired
    private Tutorial001GenericEntityRepository genericEntityRepository;

    @Test
    public void givenTutorial001GenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() {
        Tutorial001GenericEntity genericEntity = genericEntityRepository.save(new Tutorial001GenericEntity("test"));
        Tutorial001GenericEntity foundEntity = genericEntityRepository.findOne(genericEntity.getId());

        assertNotNull(foundEntity);
        assertEquals(genericEntity.getValue(), foundEntity.getValue());
    }
}

重要的是,您看到,这个Spring Boot测试具有类级别注释,以向SpringBoot测试提供配置上下文。

我们正在倾倒一个且仅一个类引用,该引用表示我们的测试配置。 tutorial.www.baeldung.com.tutorial001jpa.separateDS.Tutorial001GenericEntityIntegrationTest.ConfigureJpa.class

然后,在这个小家伙上,您可以放置所有需要的附加注释,以便SpringBoot提供应用程序配置。

在这种情况下,我们有一个专用注释来提及实体。 另一个提到存储库。 还有一个告诉SpringBoot激活其自动配置。

然后,这个SpringBoot自动配置注释会执行其他神秘操作,例如查看您的类路径并查看您是否在类路径中说:

   <dependency>
        <groupId>org.hsqldb</groupId>
        <artifactId>hsqldb</artifactId>
        <scope>test</scope>
        <version>2.3.4</version>
    </dependency>

它将立即知道如何为此数据库配置内存数据源。

在幕后,可能正在使用其他配置。 例如,如果您在src/test/resources中创建一个application.properties文件,则该文件将被视为。 很容易看到appliction.properties是否被运行测试考虑。

如果您想要验证这一点,请确保在测试设置中没有任何依赖于postgres的JDBC驱动程序。 然后将以下内容放入您的application.properties中:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

该方言不与HSQL或H2兼容,因此它会立即使您的绿色测试集成失败。

说实话,我不知道是否有一种更简单的注释组合来适当配置springboot扫描集成测试。

通常情况下,我建议您尝试避免在src/test/resources中拥有数以千计的配置类。 因为如果某个时刻,您想要将所有集成测试从applicat-postgres.proerties切换到application-hsql.properties,那么您可能需要调整多个配置类,而不仅仅是一个。

因此,作为规则,针对您编写的每个Maven组件,我会尝试让检查存储库的测试扩展某种MyBaseIntegrationTestClass,并在其中设置这个

@ContextConfiguration(classes = {
        tutorial.www.baeldung.com.tutorial001jpa.separateDS.Tutorial001GenericEntityIntegrationTest.ConfigureJpa.class })

这样你只需要使用一个配置来测试整个项目。

无论如何,希望这里提供的三个类能够帮到你。

最后一件事,关于 Maven 集成测试的依赖,我正在使用以下内容:

<!-- Test Dependencies JPA REPOSITORY TESTS -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

我使用HSQL和H2的原因是为了让我的集成测试能够调整为使用application-hsql或application-h2.properties。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接