-
Notifications
You must be signed in to change notification settings - Fork 0
/
BookRepositoryTest.java
56 lines (42 loc) · 1.98 KB
/
BookRepositoryTest.java
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package io.github.scordio.playground;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.jpa.domain.Specification;
@DataJpaTest(showSql = false) // use P6Spy
class BookRepositoryTest {
@Autowired
private BookRepository underTest;
@Autowired
private AuthorRepository authorRepository;
@Autowired
private EntityManager entityManager;
@Test
void findAllByAuthorId() {
// insert into author (name,id) values ('Homer',1);
Author homer = authorRepository.save(new Author("Homer"));
// insert into book (author_id,name,id) values (1,'Iliad',1);
underTest.save(new Book("Iliad", homer));
// insert into book (author_id,name,id) values (1,'Odyssey',2);
underTest.save(new Book("Odyssey", homer));
// select b1_0.id,b1_0.author_id,b1_0.name from book b1_0 left join author a1_0 on a1_0.id=b1_0.author_id where a1_0.id=1;
underTest.findAllByAuthorId(homer.getId());
// select b1_0.id,b1_0.author_id,b1_0.name from book b1_0 where b1_0.author_id=1;
underTest.findAllByAuthorIdWithJPQL(homer.getId());
// select b1_0.id,b1_0.author_id,b1_0.name from book b1_0 where b1_0.author_id=1;
underTest.findAll(byAuthorId(homer.getId()));
// select b1_0.id,b1_0.author_id,b1_0.name from book b1_0 where b1_0.author_id=1;
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Book> cq = cb.createQuery(Book.class);
Root<Book> root = cq.from(Book.class);
cq.select(root).where(cb.equal(root.get("author").get("id"), homer.getId()));
entityManager.createQuery(cq).getResultList();
}
private static Specification<Book> byAuthorId(Long authorId) {
return (root, query, builder) -> builder.equal(root.get("author").get("id"), authorId);
}
}