Java 如何将 Spring Boot 与 MySQL 数据库和 JPA 一起使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27981789/
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-08-11 05:24:16  来源:igfitidea点击:

How to use Spring Boot with MySQL database and JPA?

javamysqlspringjpaspring-boot

提问by somebody

I want to setting Spring Boot with MySQL and JPA. For this I create: Person

我想用 MySQL 和 JPA 设置 Spring Boot。为此我创建:

package domain;

import javax.persistence.*;

@Entity
@Table(name = "person")
public class Person {

@Id
@GeneratedValue
private Long id;

@Column(nullable = false)
private String firstName;

// setters and getters
}

PersonRepository

个人资料库

package repository;

import domain.Person;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;


public interface PersonRepository extends CrudRepository<Person, Long> {

Page<Person> findAll(Pageable pageable);
}

PersonController

个人控制器

package controller;

import domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import repository.PersonRepository;

@Controller
public class PersonController {

@Autowired
private PersonRepository personRepository;

@RequestMapping("/")
@ResponseBody
public String test() {
    Person person = new Person();
    person.setFirstName("First");
    person.setLastName("Test");
    personRepository.save(person);
    return "hello";
}
}

Start class Example:

开始课程示例

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Example {

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

}

And for database configuration, I create application.properties

对于数据库配置,我创建了application.properties

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.globally_quoted_identifiers=true

spring.datasource.url=jdbc:mysql://localhost/test_spring_boot
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver

So I have project structure:

所以我有项目结构:

enter image description here

在此处输入图片说明

But as a result I have exceptions:

但结果我有例外:

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [Example]; nested exception is java.io.FileNotFoundException: class path resource [org/springframework/security/config/annotation/authentication/configurers/GlobalAuthenticationConfigurerAdapter.class] cannot be opened because it does not exist

As a example I use: spring-boot-sample-data-jpa/pom.xml

作为一个例子,我使用: spring-boot-sample-data-jpa/pom.xml

采纳答案by Yannic Klem

I created a project like you did. The structure looks like this

我像你一样创建了一个项目。结构看起来像这样

project structure

项目结构

The Classes are just copy pasted from yours.

课程只是从您的课程中复制粘贴的。

I changed the application.propertiesto this:

我将application.properties更改为:

spring.datasource.url=jdbc:mysql://localhost/testproject
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update

But I think your problem is in your pom.xml:

但我认为你的问题出在你的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>

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

<artifactId>spring-boot-sample-jpa</artifactId>
<name>Spring Boot JPA Sample</name>
<description>Spring Boot JPA Sample</description>

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Check these files for differences. Hope this helps

检查这些文件的差异。希望这可以帮助

Update 1:I changed my username. The link to the example is now https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

更新 1:我更改了用户名。该示例的链接现在是https://github.com/Yannic92/stackOverflowExamples/tree/master/SpringBoot/MySQL

回答by wuyuexin

You can move Application.javato a folder under the java.

您可以移动Application.java到 java.util 下的文件夹。

回答by Florin Grozea

When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplicationis not enough.

将类移动到特定的包(如存储库、控制器、域)时,仅使用泛型@SpringBootApplication是不够的。

You will have to specify the base package for component scan

您必须为组件扫描指定基本包

@ComponentScan("base_package")

For JPA

对于 JPA

@EnableJpaRepositories(basePackages = "repository")

is also needed, so spring data will know where to look into for repository interfaces.

还需要,因此 spring 数据将知道在哪里查找存储库接口。

回答by linghu

In the spring boot reference,it said:

弹簧靴参考中,它说:

When a class doesn't include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.

当一个类不包含包声明时,它被认为是在“默认包”中。通常不鼓励使用“默认包”,应该避免使用。对于使用 @ComponentScan、@EntityScan 或 @SpringBootApplication 注释的 Spring Boot 应用程序,它可能会导致特定问题,因为每个 jar 中的每个类都将被读取。

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

In your cases. You must add scanBasePackagesin the @SpringBootApplicationannotation.just like@SpringBootApplication(scanBasePackages={"domain","contorller"..})

在你的情况下。您必须添加scanBasePackages@SpringBootApplicationannotation.just像@SpringBootApplication(scanBasePackages={"domain","contorller"..})