Best way to create JPA query that might contain a parameter or might not

前端 未结 1 1149
轮回少年
轮回少年 2021-01-15 16:09

there\'s method that creates JPA query like this

        String queryString = \"SELECT i FROM Item i\";

        if (null != search) {
            queryStrin         


        
1条回答
  •  心在旅途
    2021-01-15 16:31

    If you don't have to write the query in such a way that you're writing a query string, you could use the JPA Criteria API. You can see the class I call "ExampleDao" which I use for research and examples here.

    You would then add an optional where clause to it, see example below:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery criteria = cb.createQuery(Item.class);
    Root root = criteria.from(Item.class);
    criteria.select(root);
    
    if (null != search) {
        String pattern = "%pattern here%";
        criteria.where(cb.like(root.get("name"), pattern));
    }
    

    0 讨论(0)
提交回复
热议问题