2017년 6월 14일 수요일

example of JPA Example Matcher

@RunWith(SpringRunner.class)
@SpringBootTest
public class ExampleMatcherTest {
@Autowired
private ExampleRepository repository;
@Test
public void exampleTest() {
Child child = new Child();
child.setName("C");
Parent parent = new Parent();
parent.setChild(child);
ExampleMatcher matcher = ExampleMatcher.matching()
.withIgnoreNullValues()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
Example<Parent> example = Example.of(parent, matcher);
assertTrue(repository.findAll(example).size > 0);
}
}
public interface ExampleRepository extends JpaRepository<Parent, Long> {
}


Parent.java, Child.java는 생략

JPA가 생성하는 Query를 확인해보자.
join과 like를 적절하게 사용해서 생성해준다.


EDIT:
Model Class 설계할때, 초기값을 넣어주도록 했다면
`ExampleMatcher`가 생성하는 Query `where`절에 해당 값이 들어가는 점에
유의하도록 하자.

아무튼 Reflection과 함께 잘 활용하면 간단하게 구현할 수 있는 부분들이 많다.