gpt4 book ai didi

java - Spring Boot数据JPA持久化到数据库报错

转载 作者:行者123 更新时间:2023-12-02 00:33:40 27 4
gpt4 key购买 nike

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

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>{

}

Controller

@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

Spring 日志

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

最佳答案

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

@Configuration
public class LoadDatabase {

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

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

关于java - Spring Boot数据JPA持久化到数据库报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57993310/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com