springboot jpa 两个数据表,一对多,联表插入、查询 全部详细代码
时间: 2024-02-29 09:52:19 浏览: 22
好的,以下是一个示例代码,实现了在 Spring Boot JPA 中使用两个数据表,进行一对多关系的联表插入和查询:
首先,我们需要定义两个实体类,一个是主表,另一个是从表,例如:
主表实体类:
```java
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)
private List<Employee> employees;
// getters and setters
}
```
从表实体类:
```java
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id")
private Department department;
// getters and setters
}
```
在主表实体类中,我们使用了 `@OneToMany` 注解来表示一个部门可以拥有多个员工,而在从表实体类中,我们使用了 `@ManyToOne` 注解来表示一个员工只能属于一个部门。
接下来,我们需要创建对应的 Repository 接口,在这个示例中,我们分别创建了 `DepartmentRepository` 和 `EmployeeRepository` 接口,例如:
```java
public interface DepartmentRepository extends JpaRepository<Department, Long> {
}
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
```
现在,我们就可以在 Service 中编写对应的业务逻辑,例如:
```java
@Service
public class DepartmentService {
@Autowired
private DepartmentRepository departmentRepository;
@Autowired
private EmployeeRepository employeeRepository;
@Transactional
public void saveDepartmentWithEmployees() {
Department department = new Department();
department.setName("IT");
Employee employee1 = new Employee();
employee1.setName("Tom");
employee1.setAge(28);
employee1.setDepartment(department);
Employee employee2 = new Employee();
employee2.setName("Jerry");
employee2.setAge(30);
employee2.setDepartment(department);
department.setEmployees(Arrays.asList(employee1, employee2));
departmentRepository.save(department);
}
@Transactional(readOnly = true)
public Department getDepartmentById(Long id) {
return departmentRepository.findById(id).orElse(null);
}
}
```
在这个示例中,我们定义了一个 `saveDepartmentWithEmployees` 方法,用于同时插入一个部门和多个员工,这个方法通过 `@Transactional` 注解来保证事务的一致性。
我们还定义了一个 `getDepartmentById` 方法,用于根据部门 ID 查询部门信息,这个方法通过 `@Transactional(readOnly = true)` 注解来保证查询的原子性。
最后,我们可以在 Controller 中调用对应的 Service 方法,例如:
```java
@RestController
public class DepartmentController {
@Autowired
private DepartmentService departmentService;
@PostMapping("/department")
public void saveDepartmentWithEmployees() {
departmentService.saveDepartmentWithEmployees();
}
@GetMapping("/department/{id}")
public Department getDepartmentById(@PathVariable Long id) {
return departmentService.getDepartmentById(id);
}
}
```
在这个示例中,我们定义了两个接口,一个是用于插入部门和员工信息的 `POST /department` 接口,另一个是用于查询部门信息的 `GET /department/{id}` 接口。
好了,以上就是一个简单的 Spring Boot JPA 一对多关系的联表插入和查询的完整示例代码。