Spring Data Jpa 学习之 QueryByExampleExecutor 接口

JpaRepository 接口通过继承 QueryByExampleExecutor 实现简单的动态查询功能

创建 Entity

@Entity
@Data
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String company;
    private String address;
}

创建接口

public interface PersonRepository extends JpaRepository<Person, Long> {}

创建测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonRepositoryTest {

    @Autowired
    private PersonRepository personRepository;

    @Test
    public void simpleTest() {
        Person person = new Person();
        person.setName("linan");

        Example<Person> example = Example.of(person);

        Optional<Person> one = personRepository.findOne(example);
    }

    @Test
    public void matcherTest() {
        Person person = new Person();
        person.setName("linan");

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withIgnorePaths("name")
                .withIncludeNullValues()
                .withStringMatcher(ExampleMatcher.StringMatcher.ENDING);

        Example<Person> example = Example.of(person, matcher);

        Optional<Person> one = personRepository.findOne(example);

    }

    @Test
    public void configMatcherTest() {
        Person person = new Person();
        person.setName("linan");
        person.setCompany("海");

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", endsWith())
                .withMatcher("company", startsWith().ignoreCase());

        Example<Person> example = Example.of(person, matcher);
        List<Person> all = personRepository.findAll(example);
        all.forEach(x -> System.out.println(x));
    }

    @Test
    public void configMatcherLambdaTest() {
        Person person = new Person();
        person.setName("linan");
        person.setCompany("海");

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", match -> match.endsWith())
                .withMatcher("company", match -> match.startsWith().ignoreCase());

        Example<Person> example = Example.of(person, matcher);
        List<Person> all = personRepository.findAll(example);
        all.forEach(System.out::println);
    }
}

StringMatcher options

StringMatcher options

Spring Data Jpa 官方文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值