Home > Enterprise >  class java.math.BigInteger cannot be cast to class java.lang.Boolean
class java.math.BigInteger cannot be cast to class java.lang.Boolean

Time:09-29

I am trying to check whether the room name in that building exists or not.If exists, then don't save else save the data into the table.So I have written this query.

 @Query(value = "select exists(select name,building from meetingroom "  
            "where building=?1 and name=?2)",nativeQuery = true)
Boolean existsByRoom(String building,String name);

Now it is showing BigInteger cannot be cast to class java.lang.Boolean Is there any way to solve this without effecting or changing the query.

CodePudding user response:

Simplest solution is here is to use JPA derived query. Assuming your entity is MeetingRoom

Boolean existsMeetingRoomByBuildingAndName(String building, String name);

CodePudding user response:

One solution is to use java.util.Optional like below. And you need to use BigInteger instead of Boolean because query will return BigInteger value when record exist.

    @Query(value = "select exists(select name,building from meetingroom "  
                    "where building=?1 and name=?2)",nativeQuery = true)
    Optional<BigInteger> existsByRoom(String building,String name);

And in service layer, you can check if the value is present.

    Optional<BigInteger> result = 
meetingRoomRepository.existsByRoom(meetingRoomRequest.getBuilding(),meetingRoomRequest.getName());
    if(result.isPresent()){
        return true;
    }
    return false;
  • Related