Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JpaRepository with Enum: findAllByOfferState_ACTIVE. NoSuchElementException

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.

like image 650
user7337867 Avatar asked Dec 06 '22 13:12

user7337867


2 Answers

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);
}
like image 72
Cepr0 Avatar answered Feb 16 '23 01:02

Cepr0


public interface OfferRepository extends PagingAndSortingRepository<Offer, Long> {

    Page<Offer> findByOfferState(OfferState state,Pageable pageable);

}
like image 42
Barath Avatar answered Feb 16 '23 01:02

Barath