I want to get all offers with (where) OfferState equals ACTIVE - is it possible using Spring Data with only method name or I must use @Query
?
@Repository
public interface OfferRepository extends JpaRepository<Offer, Long> {
Page<Offer> findAllByOfferState_ACTIVE(Pageable pageable);
}
public enum OfferState {
ACTIVE, FINISHED
}
@Entity
@Table(name = "OFFERS")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Offer {
@Id
@GeneratedValue
private Long id;
[...]
@Enumerated(EnumType.STRING)
private OfferState offerState;
}
@Service
public class OfferServiceImpl implements OfferService {
@Autowired
private OfferRepository offerRepository;
@Override
public Offer saveOffer(Offer offer) {
offer.setOfferState(OfferState.ACTIVE);
return offerRepository.save(offer);
}
@Override
public Page<Offer> getAllByPage(Pageable pageable) {
Page<Offer> allByOfferState_active = offerRepository.findAllByOfferStateACTIVE(pageable);
return allByOfferState_active;
}
}
Is findAllByOfferState_ACTIVE
incorrect? When I do GET, then in my service method getAllByPage
throws an exception Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.NoSuchElementException] with root cause
.
I tried with @Enumerated(EnumType.STRING)
and without it, but still the same.
You can create a default interface method:
public interface OfferRepository extends JpaRepository<Offer, Long> {
default List<Offer> findAllWhereOfferStateIsActive() {
return findByOfferState(OfferState.ACTIVE);
}
List<Offer> findByOfferState(OfferState state);
}
public interface OfferRepository extends PagingAndSortingRepository<Offer, Long> {
Page<Offer> findByOfferState(OfferState state,Pageable pageable);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With