Passing empty list as parameter to JPA query throws error

后端 未结 7 1787
无人共我
无人共我 2020-12-05 22:52

If I pass an empty list into a JPA query, I get an error. For example:

List municipalities = myDao.findAll();  // returns empty list
em.c         


        
7条回答
  •  半阙折子戏
    2020-12-05 23:40

    If you are using spring/hibernate annotations then one of the easiest ways of working around this is having two parameters. First lets define our JPA annotation:

            + "AND (p.myVarin :state OR :nullCheckMyVar is null) "
    

    Then pass those parameters in as normal:

        @Param("myVarin") List myVarin,
        @Param("nullCheckMyVar") Integer nullCheckMyVar,
    

    Finally in what ever service call you can do the following:

        Integer nullCheckInteger = null;
        if (myVarIn != null && !myVarIn.isEmpty()) {
            // we can use any integer
            nullCheckInteger = 1;
        }
        repo.callService(myVarIn, nullCheckInteger);
    

    And then pass those two parms into the call.

    What does this do? If myVarIn is not null and filled then we can specify "all" as 1 != null. Otherwise we pass in our list and null is null and therefore ignored. This either selects "all" when empty or something when not empty.

提交回复
热议问题