2

I am using Spring Data JPA with native queries like below

public interface ItemRepository extends JpaRepository<ItemEntity, Long> {

  @Query(value = "select * from items i where i.category = :itemCategory and i.item_code = :itemCode", nativeQuery = true)
  Page<ItemEntity> search(@Param("itemCategory") String itemCategory, @Param("itemCode") String itemCode, Pageable pageable);
}

Now, my use case is

  1. It itemCode is available, only the item with that code from that category should be returned.
  2. But if itemCode is not available then all items in that category should be returned.

So the problem with the above category is when itemCode is passed as NULL no data is returned since it does not match anything. whereas the requirement is it should be ignored.

So is there a way to optionally add a clause to Spring Data JPA native query. I know it is possible with CriteriaQuery but can we do something similar for native queries?

Thanks

1
  • Look at using the querydsl extension. That would let you call by either category, code or category and code without having to write any query implementations. Commented Sep 5, 2019 at 13:46

2 Answers 2

1

Yes, it's feasible with native query too. Very Good explanation here read this

#Approach1

@NamedQuery(name = "getUser", query = "select u from User u"
            + " where (:id is null or u.id = :id)"    
            + " And :username"

:itemCode is null or i.item_code = :itemCode

#Approach2

# UserDao.java 

  public User getUser(Long id, String usename) {
        String getUser = "select u from user u where u.id " + Dao.isNull(id) 
                       + " And u.username " + Dao.isNull(username);
        Query query = Dao.entityManager.createQuery(getUser);
    }

# Dao.java

   public static String isNull(Object field) {
        if (field != null) {
                if (field instanceof String) {
                    return " = " + "'" + field + "'";
                } else {
                    return " = " + field;
                }

            } else {
                return " is NULL ";
            }
    }

How to handle null value of number type in JPA named query

Sign up to request clarification or add additional context in comments.

Comments

0

Just modify the where condition

i.item_code = :itemCode

to

:itemCode is null or i.item_code = :itemCode

3 Comments

That is not what is being asked.
sorry, why not ?
If the passed param is null then ignore it otherwise return matching. Your answer does something else entirely. Essentially, do not add the condition i.item_code = :itemCode if it param is null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.