SELECT * FROM department d JOIN employee c ON c.department_id = d.id WHERE d.id = 1,转成springboot+jpa全部代码
时间: 2024-03-01 13:51:27 浏览: 136
假设你已经创建好了Department和Employee实体类,并且已经配置好了数据库连接。
首先,创建一个JpaRepository接口,用于处理Department实体类和数据库之间的交互:
```java
@Repository
public interface DepartmentRepository extends JpaRepository<Department, Long> {
List<Employee> findByDepartmentId(Long id);
}
```
然后,在需要使用的地方注入DepartmentRepository,并使用它来查询数据:
```java
@Service
public class MyService {
@Autowired
private DepartmentRepository departmentRepository;
public List<Employee> getEmployeesByDepartmentId(Long id) {
return departmentRepository.findByDepartmentId(id);
}
}
```
在上面的代码中,我们通过departmentRepository调用findByDepartmentId方法查询符合条件的Employee对象并返回。
最后,我们只需要在Controller中调用MyService中的方法即可:
```java
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/employees/{departmentId}")
public List<Employee> getEmployeesByDepartmentId(@PathVariable Long departmentId) {
return myService.getEmployeesByDepartmentId(departmentId);
}
}
```
这样,当我们访问"/employees/1"时,就会返回id为1的Department下的所有Employee对象。
阅读全文