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)));
        }
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM