springboot一对多查询
时间: 2023-05-25 18:03:56 浏览: 322
在SpringBoot中进行一对多查询的方法如下:
1.创建实体类
创建两个实体类实现一对多的关系,并在其中使用@OneToMany和@ManyToOne进行相应的注解。
2.创建DAO
创建两个DAO层,并在其中对应的实体类使用@ManyToMany和@OneToMany进行查询操作。
3.创建Service
创建对应的Service层,将两个DAO层进行整合,使其能够相互调用。
4.创建Controller
创建对应的Controller层,通过调用Service中的方法,获取数据并返回给前端页面。
示例代码:
```java
//Student实体类
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
private List<Book> books = new ArrayList<>();
//getter and setter
}
//Book实体类
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "name")
private String name;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "student_id")
private Student student;
//getter and setter
}
//StudentDAO
@Repository
public interface StudentDAO extends JpaRepository<Student, Long> {}
//BookDAO
@Repository
public interface BookDAO extends JpaRepository<Book, Long> {
List<Book> findByStudentId(long studentId);
}
//StudentService
@Service
public class StudentService {
private StudentDAO studentDao;
private BookDAO bookDao;
@Autowired
public void setStudentDao(StudentDAO studentDao) {
this.studentDao = studentDao;
}
@Autowired
public void setBookDao(BookDAO bookDao) {
this.bookDao = bookDao;
}
public List<Student> findAll() {
return studentDao.findAll();
}
public List<Book> findBooksByStudentId(long studentId) {
return bookDao.findByStudentId(studentId);
}
}
//StudentController
@RestController
@RequestMapping("/students")
public class StudentController {
private final StudentService studentService;
@Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
@GetMapping
public List<Student> findAll() {
return studentService.findAll();
}
@GetMapping("/{studentId}/books")
public List<Book> findBooksByStudentId(@PathVariable long studentId) {
return studentService.findBooksByStudentId(studentId);
}
}
```
以上就是SpringBoot进行一对多查询的完整流程,通过以上步骤,就能够在SpringBoot中实现简单的一对多查询操作。