java Spring boot - 使用 JPA 在关系数据库中存储和检索数据时出现 UnsatisfiedDependencyException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35189047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:51:02  来源:igfitidea点击:

Spring boot - UnsatisfiedDependencyException when using JPA to store and retrieve data in a relational database

javaspringhibernatespring-mvcjpa

提问by Declan Fitzpatrick

I've tried to build an application that uses Spring Data JPA to store and retrieve data in a relational database using Spring boot. I've been following guide on the spring site but continue to get this error. Does anyone know the cause of this or what I could do to fix it? Would be much appreciated, thanks.

我尝试构建一个应用程序,该应用程序使用 Spring Data JPA 在使用 Spring boot 的关系数据库中存储和检索数据。我一直在遵循 spring 站点上的指南,但继续收到此错误。有谁知道这是什么原因或我能做些什么来解决它?将不胜感激,谢谢。

 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'commandLine' defined in com.example.Application: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.example.ImageRepository]: : Error creating bean with name 'imageRepository': Cannot create inner bean '(inner bean)#391c56d7' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#391c56d7': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'imageRepository': Cannot create inner bean '(inner bean)#391c56d7' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#391c56d7': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined

The code is below:

代码如下:

The repository:

存储库:

package com.example;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

 public interface ImageRepository extends CrudRepository<Image, Long> {

     List<Image> findByImageID(long imageID);
}

The application:

应用程序:

@SpringBootApplication
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

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

    @Bean
    public CommandLineRunner commandLine(ImageRepository repository) {
        return (args) -> {
            repository.save(new Image("image1",50,40));
            repository.save(new Image("image2",50,40));
            repository.save(new Image("image3",50,40));
            repository.save(new Image("image4",50,40));
            repository.save(new Image("image5",50,40));

            log.info("Customers found with findAll():");
            log.info("-------------------------------");
            for (Image image : repository.findAll()) {
                log.info(image.toString());
            }
            log.info("");

            Image image = repository.findOne(1L);
            log.info("Image found with findOne(1L):");
            log.info("--------------------------------");
            log.info(image.toString());
            log.info("");

            log.info("Image found with findByImageID(1):");
            log.info("--------------------------------------------");
            for (Image im : repository.findByImageID(1)) {
                log.info(im.toString());
            }
            log.info("");
        };
    }
}

The entity

实体

@Entity
public class Image {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long imageID;
    private double lat, lon;
    private String description = "";

    protected Image() {}

    Image(String description, double lat, double lon)
    {
        this.description = description;
        this.lat = lat;
        this.lon = lon;

    }
    Image(double lat, double lon)
    {
        this.lat = lat;
        this.lon = lon;
    }

    public long getID()
    {
        return imageID;
    }
    public String getDesc()
    {
        return description;
    }
    public double getLat()
    {
        return lat;
    }
    public double getLon()
    {
        return lon;
    }

    @Override
    public String toString() {
        return String.format(
                "Image[id=%d, description='%s', lat='%d', lon='%d']",
                imageID, description,lat,lon);
    }

}

POM

聚甲醛

<?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>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>   

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>   
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

回答by romixch

Now I had the time to test it on my machine. The problem is that you are missing a jpa implementation. By adding a dependency to spring-data-jpa and and persistence-api you only get the interfaces. If you replace those two dependencies with spring-boot-starter-data-jpa, you will actually get a hibernate entitymanager implementation.

现在我有时间在我的机器上测试它。问题是您缺少 jpa 实现。通过向 spring-data-jpa 和 persistence-api 添加依赖项,您只能获得接口。如果你用 spring-boot-starter-data-jpa 替换这两个依赖项,你实际上会得到一个 hibernate entitymanager 实现。

This is the pom.xml I successfully tested:

这是我测试成功的 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>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

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

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring4</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>   
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>