spring-boot-starter-data-jpa 中的 Eaxmple 如何使用

本文只简单介绍精确匹配(sql中 'where ** = **')、字符串搜索(sql中'where ** like %name%')。

如果需要更多高级应用,可以参考spring jpa官方示例,传送门

 

一.准备工作

1.创建一个标准的spring boot jpa程序,并配置数据库连接

pom.xml

...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

...

2.实体类 User.java

...
@Entity
public class User {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    private Short type;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", type=" + type +
                '}';
    }
//... setter / getter..
}

3.Repository UserRepository.java

...
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer> {}

二.测试程序 UserService.java ,运行 Application 即可看到结果

@Component
@Transactional
public class UserService {


    private final UserRepository userRepository;

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;

        //初始化数据
        init();

        //测试查新
        printAll("通过 Example 精确查找数据", queryByExample());
        printAll("通过 Example 字符串匹配", queryByExampleMatcher());
    }


    Collection<User> queryByExample() {
        User user = new User();
        user.setType((short) 1);

        Example<User> userExample = Example.of(user);

        return userRepository.findAll(userExample);

    }

    Collection<User> queryByExampleMatcher() {

        User user = new User();
        user.setName("10010");

        Example<User> userExample = Example.of(user, ExampleMatcher.matching().withMatcher("name",
                /*startsWith -> 10010%
                * endsWith -> %10010
                * contains -> %10010%
                * */
                ExampleMatcher.GenericPropertyMatchers.startsWith()));

        return userRepository.findAll(userExample);
    }


    void printAll(String pre, Collection<User> userIterator) {
        logger.info("遍历 用户列表 {}", pre);

        for (User u : userIterator) {
            logger.info(u.toString());
        }
    }


    void init() {
        for (int i = 0; i < 443; i++) {
            userRepository.save(new User(("100" + i + "00111" + i), (short) (i % 3)));
        }
    }
    
}

 

posted @ 2017-03-04 12:47  Parasis  阅读(3533)  评论(0编辑  收藏  举报