如何将Spring Boot与MySQL数据库和JPA一起使用?
2022-09-01 12:15:31
我想用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
}
人员存储库
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);
}
人员控制器
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