Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set that a Spring Data JPA query method have to be a parameter value always set as true?

I am not so into Hibernate and Spring Data JPA and I have the following doubt.

I have this method signature that correctly perform a query:

@Repository
public interface AccomodationMediaDAO extends JpaRepository<AccomodationMedia, Long> {

    AccomodationMedia findByIdAccomodationAndIsMaster(Long accomodationId, boolean isMaster);

}

It finds (on the table mapped by the AccomodationMedia entity class) a single record having the field named idAccomodation setted with the Long value represented by the accomodationId method parameter and the field isMaster reppresented by the isMaster boolean.

It works fine but my "problem" is that doing in this way I have always to explicitly pass the value of the boolean isMaster parameter.

This parameter has to be always set as true, so I tried to change the previous method signature in this way:

AccomodationMedia findByIdAccomodationAndIsMaster(Long accomodationId, true);

but IntelliJ displays an error: Identifier or type expected.

Why? Can I set that the value of this parameter have to be explicitly set to the true boolean value?

like image 807
AndreaNobili Avatar asked Nov 14 '16 16:11

AndreaNobili


2 Answers

As described in the reference documentation you can just use the IsTrue keyword:

AccomodationMedia findByIdAccomodationAndIsMasterIsTrue(Long accomodationId);
like image 100
Oliver Drotbohm Avatar answered Sep 27 '22 21:09

Oliver Drotbohm


If you're using Java 8, you can overload it with a default implementation:

public interface AccomodationMediaDAO extends JpaRepository<AccomodationMedia, Long> {

    AccomodationMedia findByIdAccomodationAndIsMaster(Long accomodationId, boolean isMaster);

    default AccomodationMedia findByIdAccomodationAndIsMaster(Long accomodationId) {
       return findByIdAccomodationAndIsMaster(accomodationId, true);
    }
}

But you can't provide a default value to a method parameter. E.g. see this question.

like image 36
radoh Avatar answered Sep 27 '22 20:09

radoh