【发布时间】:2021-11-18 06:41:56
【问题描述】:
几天前我开始学习休眠 JPA,但我无法找到以下给定问题的解决方案
我的项目由三类员工、电话、部门组成,通过查看代码您可以轻松了解我在做什么。
当我尝试使用 Spring Boot 控制器将此数据保存到数据库中时,出现的主要问题是它在列中显示空值。在员工表中,department_id 为空(不是使用 cascade.All 自动更新),在电话表中,employee_id 为空。
我不想手动更新。他们有什么办法让 dep_id 和 emp_id 自动更新到外键表。
{
"name":"CSE",
"employees":[
{
"name":"Welcome",
"age":23,
"phones":[{"number":1234567890},{"number":1234567890}]
},
{
"name":"back",
"age":25,
"phones":[{"number":1234567890},{"number":1234567890}]
}
]
}
package com.example.entity;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private int age;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
@OneToMany(mappedBy = "employee", cascade=CascadeType.ALL)
private List<Phone> phones;
// getters and setters...
}
package com.example.entity;
import javax.persistence.*
@Entity
public class Phone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String number;
@ManyToOne
@JoinColumn(name = "employee_id")
private Employee employee;
// getters and setters...
}
package com.example.entity;
import javax.persistence.*;
import java.util.List;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
@OneToMany(mappedBy = "department",cascade = CascadeType.ALL)
private List<Employee> employees;
}
dept table in database
id name
1 CSE
employee table
id name age department_id
1. welcome 23. null
2. back. 25. null
phone table
id number employee_id
1. 1234567890. null
2. 1234567890. null
3. 1234567890 null
4. 1234567890. null
为什么employee_id 和department_id 没有在级联中自动更新全部
Controller class
package com.example.controller;
import com.example.dao.DepRepo;
import com.example.dao.EmployeeRepo;
import com.example.dao.PhoneRepo;
import com.example.entity.Department;
import com.example.entity.Employee;
import com.example.service.FakeService;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import jakarta.inject.Inject;
@Controller("/dummy")
public class DummyController {
@Inject
FakeService fakeService;
@Inject
PhoneRepo phoneRepo;
@Inject
EmployeeRepo employeeRepo;
@Inject
DepRepo depRepo;
@Get ("/")
public String fun(){
fakeService.fun();
return "welcome back";
}
@Post("/add")
public HttpResponse<?> fun(@Body Department dep){
System.out.println(dep);
depRepo.save(dep);
return HttpResponse.status(HttpStatus.ACCEPTED).body("data add successfully");
}
}
【问题讨论】:
标签: spring-boot hibernate jpa hibernate-mapping cascade