【问题标题】:How to use Spring Boot with MySQL database and JPA?如何将 Spring Boot 与 MySQL 数据库和 JPA 一起使用?
【发布时间】:2015-03-14 22:18:52
【问题描述】:

我想用 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";
}
}

开始类示例

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);
}

}

对于数据库配置,我创建 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

所以我有项目结构:

但结果我有例外:

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

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

【问题讨论】:

  • 该链接应该告诉我们什么?这是 Spring Boot Data JPA 示例的 1.2.2.BUILD-SNAPSHOT 的 pom.xml。另外,您是如何运行该应用程序的?
  • @Steve,我在 IDE IDEA 中运行我的 Example.java
  • 是否从命令行运行?
  • 不是答案。但是,如果您遇到问题,您可能正在使用已弃用的驱动程序类名称。请改用spring.datasource.driverClassName=com.mysql.cf.jdbc.Driver

标签: java mysql spring jpa spring-boot


【解决方案1】:

我像你一样创建了一个项目。结构是这样的

这些课程只是从您的课程中复制粘贴而来。

我将 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

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

检查这些文件是否存在差异。希望这会有所帮助

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

【讨论】:

  • 我复制您的更改。很伤心,但我还有例外Caused by: java.io.FileNotFoundException: class path resource [org/springframework/security/config/annotation/authentication/configurers/GlobalAuthenticationConfigurerAdapter.class] cannot be opened because it does not exist
  • 那么你的项目比你向我们展示的要多。您的问题与弹簧安全有关。你的 maven 依赖项中还有 spring 安全性吗?
  • 不,我没有。我展示了我所有的架构和课程。
  • 等一下。我会将我的项目上传到 GitHub,以便您可以从那里获取它。它应该与您的项目完全相同,并且可以正常工作。
  • 您的代码确实有效!而且我找不到你的项目和我的项目有什么不同。无论如何,谢谢!
【解决方案2】:

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

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

@ComponentScan("base_package")

对于 JPA

@EnableJpaRepositories(basePackages = "repository")

也是需要的,所以 spring data 会知道在哪里寻找存储库接口。

【讨论】:

  • 嗯是和不是。如果您使用@SpringBootApplication,您的所有组件都必须处于与@SpringBootApplication 注释的类相同或更低的级别。在此示例中就是这种情况,因此不需要 @ComponentScan
【解决方案3】:

spring boot reference,它说:

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

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

在你的情况下。你必须在@SpringBootApplication注解中添加scanBasePackages。就像@SpringBootApplication(scanBasePackages={"domain","contorller"..})一样

【讨论】:

    【解决方案4】:

    对于基于 Jpa 的应用程序:基础包扫描 @EnableJpaRepositories(basePackages = "repository") 您可以尝试一次!!!
    项目结构

    com
     +- stack
         +- app
         |   +- Application.java
         +- controller
         |   +- EmployeeController.java
         +- service
         |   +- EmployeeService.java
         +- repository
         |   +- EmployeeRepository.java
         +- model
         |   +- Employee.java
    -pom.xml
    dependencies: 
        mysql, lombok, data-jpa
    

    application.properties

    #Data source :
    spring.datasource.url=jdbc:mysql://localhost:3306/employee?useSSL=false
    spring.datasource.username=root
    spring.datasource.password=root
    spring.jpa.generate-ddl=true
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    
    #Jpa/Hibernate :
    spring.jpa.show-sql=true
    spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
    spring.jpa.hibernate.ddl-auto = update
    

    Employee.java

    @Entity
    @Table (name = "employee")
    @Getter
    @Setter
    public class Employee {
    
        @Id
        @GeneratedValue (strategy = GenerationType.IDENTITY)
        private Long id;
    
        @Column (name = "first_name")
        private String firstName;
        @Column (name = "last_name")
        private String lastName;
        @Column (name = "email")
        private String email;
        @Column (name = "phone_number")
        private String phoneNumber;
        @Column (name = "emp_desg")
        private String desgination;
    }
    

    EmployeeRepository.java

    @Repository
    public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    }
    

    EmployeeController.java

    @RestController
    public class EmployeeController {
    
        @Autowired
        private EmployeeService empService;
    
        @GetMapping (value = "/employees")
        public List<Employee> getAllEmployee(){
            return empService.getAllEmployees();
        }
    
        @PostMapping (value = "/employee")
        public ResponseEntity<Employee> addEmp(@RequestBody Employee emp, HttpServletRequest 
                                             request) throws URISyntaxException {
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(new URI(request.getRequestURI() + "/" + emp.getId()));
            empService.saveEmployee(emp);
            return new ResponseEntity<Employee>(emp, headers, HttpStatus.CREATED);
        }
    

    EmployeeService.java

    public interface EmployeeService {
        public List<Employee> getAllEmployees();
        public Employee saveEmployee(Employee emp);
    }
    
    

    EmployeeServiceImpl.java

    @Service
    @Transactional
    public class EmployeeServiceImpl implements EmployeeService {
    
        @Autowired
        private EmployeeRepository empRepository;
    
        @Override
        public List<Employee> getAllEmployees() {
            return empRepository.findAll();
        }
    
        @Override
        public Employee saveEmployee(Employee emp) {
            return empRepository.save(emp);
        }
    }
    
    

    EmployeeApplication.java

    @SpringBootApplication
    @EnableJpaRepositories(basePackages = "repository")
    public class EmployeeApplication {
        public static void main(String[] args) {
            SpringApplication.run(EmployeeApplication.class, args);
        }
    }
    

    【讨论】:

      【解决方案5】:

      您的代码在默认包中,即您在 src/main/java 中拥有所有文件,但没有自定义包。我强烈建议你创建包 n 然后将源文件放入其中。

      Ex-
       src->
           main->
                java->
                      com.myfirst.example
                         Example.java
                      com.myfirst.example.controller
                         PersonController.java
                      com.myfirst.example.repository
                        PersonRepository.java
                      com.myfirst.example.model
                         Person.java
      

      希望它能解决你的问题。

      【讨论】:

        【解决方案6】:

        请添加mysql-connector-java依赖

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
        

        并在 application.properties

        中添加以下提到的属性
        # Data Source properties
        spring.datasource.url=jdbc:mysql://localhost:3306/yourDatabaseName?useSSL=false
        spring.datasource.username=root
        spring.datasource.password=YourPassword
        spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
        
        # JPA properties 
        spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
        spring.jpa.show-sql=true
        # Hibernate ddl auto (create, create-drop, validate, update)
        spring.jpa.hibernate.ddl-auto = update
        

        【讨论】:

          【解决方案7】:

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

          【讨论】:

          • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方发表评论 - 您可以随时评论自己的帖子,一旦您有足够的reputation,您就可以comment on any post。 - From Review
          • 我尝试运行应用程序并得到相同的异常,将主类移动到文件夹后,应用程序可以运行成功。
          猜你喜欢
          • 2020-02-07
          • 1970-01-01
          • 1970-01-01
          • 2021-12-13
          • 2019-06-08
          • 1970-01-01
          • 1970-01-01
          • 2023-03-18
          • 1970-01-01
          相关资源
          最近更新 更多