Привет всем!
В процессе изучения spring data, появился следующий вопрос.
Допустим есть 2 сущности, студенты и книги. У одного студента может быть несколько книг. Вот примерные entity:
Student.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
@Entity
@Table (name="Student")
class Student {
@Id
@Column (name="student_id")
private int id;
@Column (name="name")
private String name;
@OneToMany(fetch = FetchType.EAGER, mappedBy = ("student"),cascade = CascadeType.ALL)
private Set<Book> book = new HashSet<Book>();
........................................................................................................
}
Book.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
@Entity
@Table(name="Book")
class Book {
@Id
@Column (name="book_id")
private int id;
@Column (name="name")
private String name;
@ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="student_id", nullable = false)
private Student student;
........................................................................................................
}
Есть репозитории:
1.
2.
3.
4.
public interface StudentRepository extends JpaRepository<Student, Integer>{
}
public interface BookRepository extends JpaRepository<Book, Integer> {
}
Вот так реализованы сервисы:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentRepository studentRepository;
@Override
public List<Student> getAllStudents() {
return studentRepository.findAll();
}
}
Аналогично реализован сервис для
Book , код приводить не буду.
Ну и класс контролер:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
@Controller
public class MainController {
private StudentService studentService;
private BookService bookService;
@Autowired(required = true)
@Qualifier(value = "studentService")
public void setStudentService(StudentService studentService) {
this.studentService = studentService;
}
@Autowired(required = true)
@Qualifier(value = "bookService")
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
@RequestMapping(value="/students", method=RequestMethod.GET)
public @ResponseBody List<Student> getStudents() {
return studentService.getAllStudents();
}
.................................................................
В базу данных внес пару записей и вызвал url /students в браузере, получил кучу вложенных данных:
1.
2.
3.
4.
5.
[{"id":1,"name":"Misha","book":[{"id":4,"name":"Thinking in Java",
"student":{"id":1,"name":"Misha","book":[{"id":4,"name":"Thinking in Java",
"student":{"id":1,"name":"Misha","book":[{"id":4,"name":"Thinking in Java",
"student":{"id":1,"name":"Misha","book":[{"id":4,"name":"Thinking in Java",
"student":{"id":1,"name":"Misha","book":[{"id":4,"name":"Thinking in Java","student":....