【问题标题】:Spring Boot data JPA persistence to database errorSpring Boot数据JPA持久性到数据库错误
【发布时间】:2020-01-19 10:38:09
【问题描述】:

我正在使用 spring boot data jpa 做一个项目。工作、国家、部门和员工表。我用控制器编写了一个方法,并手动创建和关联了对象。但是,当我运行我的应用程序时,我没有遇到任何错误,但没有向我的数据库添加任何记录,也没有创建我的表。可能是什么原因?我在下面与您分享我的代码。谢谢。

project structure

工作

@Entity
@Table(name="jobs")
public class Jobs {

    @Id
    @GeneratedValue
    @NotNull
    @Column
    private int id;

    @Column
    private String title;

    @Column
    private int salary;

    @Column
    private String currency;

    @ManyToMany
    private List<Departments> departments;

    //G&S
}

国家

@Entity
@Table(name="country")
public class Country {

    @Id
    @GeneratedValue
    @NotNull
    @Column
    private int id;

    @NotNull
    @Column
    private String country;

    @NotNull
    @Column
    private String city;

    @NotNull
    @Column
    private String district;

    //G&S
}

部门

@Entity
@Table(name = "departments")
public class Departments {

    @Id
    @GeneratedValue
    @NotNull
    @Column
    private int id;

    @NotNull
    @Column
    private String department;

    @OneToMany
    private Country country;

    //G&S
}

员工

@Entity
@Table(name="employee")
public class Employee {

    @Id
    @GeneratedValue
    @NotNull
    @Column
    private int id;

    @Column
    private String firstName;

    @Column
    private String lastName;

    @OneToMany
    private Jobs jobs;

    //G&S
}

工作、国家、部门和员工信息库是 JPA 信息库

员工资料库

public interface EmployeeRepository extends JpaRepository<Employee, Integer>{

}

控制器

@RestController

public class MainController {

    @Autowired
    JobsRepository jobsRepository;

    @Autowired
    CountryRepository countryRepository;

    @Autowired
    DepartmentsRepository departmentsRepository;

    @Autowired
    EmployeeRepository employeeRepository;

    Jobs jobs;
    Country country;
    Departments departments;
    Employee employee;
    List<Departments> departmentsList;


    @GetMapping("/generate")
    public String generateManual() {

        try {
            country = new Country();
            country.setCountry("Turkey");
            country.setCity("Istanbul");
            country.setDistrict("Pendik");
            countryRepository.save(country);

            departments = new Departments();
            departments.setDepartment("IT");
            departments.setCountry(country);
            departmentsRepository.save(departments);

            jobs = new Jobs();
            jobs.setTitle("Software Developer");
            jobs.setSalary(4000);
            jobs.setCurrency("TL");
            departmentsList = new ArrayList<Departments>();
            jobs.setDepartments(departmentsList);
            jobsRepository.save(jobs);

            employee = new Employee();
            employee.setFirstName("Mutlu");
            employee.setLastName("EREN");
            employee.setJobs(jobs);
            employee.setJobs(jobs);
            employeeRepository.save(employee);

                return "GENERATED SUCCESSFULLY";

            }catch(Exception e) {
                return "FAILED";
            }           
    }
}

应用程序属性

spring.datasource.url=jdbc:mysql://localhost:3306/jobs?useUnicode=true&characterEncoding=UTF-8&useLegacyDatetimeCode=false&serverTimezone=Turkey
spring.datasource.username=root
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

春季日志

2019-09-18 12:41:11.375  INFO 28594 --- [           main] com.example.sec.JobsApplication          : Starting JobsApplication on meren-HP-Pavilion-15-Notebook-PC with PID 28594 (/home/meren/Documents/workspace-sts-3.9.9.RELEASE/jobs/target/classes started by meren in /home/meren/Documents/workspace-sts-3.9.9.RELEASE/jobs)
2019-09-18 12:41:11.378  INFO 28594 --- [           main] com.example.sec.JobsApplication          : No active profile set, falling back to default profiles: default
2019-09-18 12:41:12.082  INFO 28594 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-18 12:41:12.108  INFO 28594 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 12ms. Found 0 repository interfaces.
2019-09-18 12:41:12.442  INFO 28594 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d99ff66a] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-18 12:41:12.706  INFO 28594 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-09-18 12:41:12.736  INFO 28594 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-09-18 12:41:12.736  INFO 28594 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.24]
2019-09-18 12:41:12.819  INFO 28594 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-09-18 12:41:12.819  INFO 28594 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1402 ms
2019-09-18 12:41:12.991  INFO 28594 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-09-18 12:41:13.092  INFO 28594 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-09-18 12:41:13.126  INFO 28594 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-09-18 12:41:13.164  INFO 28594 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.11.Final}
2019-09-18 12:41:13.164  INFO 28594 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-09-18 12:41:13.257  INFO 28594 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-09-18 12:41:13.340  INFO 28594 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-09-18 12:41:13.516  INFO 28594 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-09-18 12:41:13.721  INFO 28594 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-18 12:41:13.751  WARN 28594 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-09-18 12:41:13.926  INFO 28594 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-18 12:41:13.928  INFO 28594 --- [           main] com.example.sec.JobsApplication          : Started JobsApplication in 2.886 seconds (JVM running for 3.508)
2019-09-18 12:41:19.393  INFO 28594 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-09-18 12:41:19.393  INFO 28594 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-09-18 12:41:19.409  INFO 28594 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 16 

http://localhost:8080/generate

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Sep 18 16:05:28 EET 2019
There was an unexpected error (type=Not Found, status=404).
No message available

【问题讨论】:

  • 那么当你调用/generate时,返回了什么?当您遇到异常时,您应该打印堆栈跟踪,这样您就有办法知道出了什么问题并修复它。
  • @Kayaman 我刚刚添加到底部
  • 你能检查一下 mysql-connector jar 文件它在 maven 构建中可用吗?并检查您使用的是哪个数据库,因为在 Spring Boot 中默认数据库是 H2
  • @okoreni 将 e.printStackTrace() 放入您的 catch 块中(或者 logger.error(e) 如果您配置了 Logger)。这样,您将看到实际的异常堆栈跟踪。现在您看到的只是缺少错误页面的 404。
  • @BheemSingh 我的依赖项是正确的,我找不到错误在哪里

标签: java hibernate spring-boot spring-data-jpa


【解决方案1】:

使用您的代码,只有在您执行GET /generate 时才会添加记录,因此在您运行应用程序时数据库为空是正常的。 如果你想用一些记录预加载数据库,我建议创建一个这样的配置类:

@Configuration
public class LoadDatabase {

    @Bean
    CommandLineRunner initDatabase(MyRepository repository) {
        return args -> {
            repository.save(...);
        };
    }
}

这样您就不必每次想要生成数据库时都向 API 发出请求。

【讨论】:

    【解决方案2】:

    根据您的描述,我了解到您有两个问题。

    1) 未创建数据库表。

    我有同样的问题,我尝试通过更改我的数据库配置来解决数据库创建问题。

    spring.datasource.url=jdbc:mysql://localhost:3306/myDbSchema?createDatabaseIfNotExist=true
    spring.datasource.username=root
    spring.datasource.password=
    spring.datasource.driverClassName=com.mysql.jdbc.Driver
    spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
    spring.jpa.hibernate.ddl-auto=create
    spring.profiles.active=prod
    

    2) 此应用程序没有显式映射 /error,因此您将其视为后备。

    这里 spring boot 正在尝试查找名为“错误”的页面。所以这意味着我认为你正在使用 Spring MVC。因此,如果在运行时发生任何错误,MVC 视图解析器将查找错误页面。

    并且您的错误消息还显示“出现意外错误(类型=未找到,状态=404)。”所以我怀疑它正在尝试查找名为“生成成功”的页面以表示无异常情况或“失败”表示异常情况,但它没有找到该页面,这就是它给出错误代码 404 的原因

    如果您只想返回纯字符串,请更改您的 get api,如下所示。

    @GetMapping("/generate")
    public ResponseEntity<String> generateManual() {
    
        try {
            country = new Country();
            country.setCountry("Turkey");
            country.setCity("Istanbul");
            country.setDistrict("Pendik");
            countryRepository.save(country);
    
            departments = new Departments();
            departments.setDepartment("IT");
            departments.setCountry(country);
            departmentsRepository.save(departments);
    
            jobs = new Jobs();
            jobs.setTitle("Software Developer");
            jobs.setSalary(4000);
            jobs.setCurrency("TL");
            departmentsList = new ArrayList<Departments>();
            jobs.setDepartments(departmentsList);
            jobsRepository.save(jobs);
    
            employee = new Employee();
            employee.setFirstName("Mutlu");
            employee.setLastName("EREN");
            employee.setJobs(jobs);
            employee.setJobs(jobs);
            employeeRepository.save(employee);
                return new ResponseEntity<>("GENERATED SUCCESSFULLY", HttpStatus.OK);
    
    
            }catch(Exception e) {
                return new ResponseEntity<>("Failed", HttpStatus.BAD_REQUEST);
            }           
    }
    

    }

    【讨论】:

      【解决方案3】:

      第一个问题是你的控制器方法根本没有被调用。 (这就是你得到 404 的原因)

      我相信它甚至没有被 Spring 注册。

      根据您提供的项目结构,您的 Spring Application 主类位于 com.example.sec 包中,而其他包(包括控制器包)NOT 在该包下。默认情况下,Spring Boot 仅扫描应用程序类的子包以查找带注释的类/方法,因此您基本上运行的是一个空的 Spring Boot 应用程序。 这也解释了为什么没有创建你的表:Spring Boot 也没有扫描你的实体。

      将您的主类移动到 com.example 包中。

      在你修复它之后,你可能会遇到一些 JPA 异常。

      当您使用 save(object) 保存对象时,它返回 持久对象。所以你需要将返回的对象作为属性添加到父对象,而不是原始对象。

      如果您覆盖原始解决方案,则最简单(但不是最好)的解决方案:

      country = countryRepository.save(country);
      ...
      departments = departmentsRepository.save(departments);
      ...
      

      第三个问题是 MainController 中的类变量。尽管这只是一个测试项目,但这是一种极其危险的做法。 jobs, country, departments,... 应该是控制器方法中的局部变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-19
        • 2021-12-26
        • 2017-06-12
        • 2017-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多