Mikhail Kopylov
Mikhail Kopylov

Reputation: 2058

What's the correct way to find all entities ordered by field in Spring Data?

I'm using Spring Data JPA and want to add a method in my base Repository interface to get all entities ordered by field order:

@NoRepositoryBean
public interface OrderedEntityDao<T extends OrderedEntity> extends EntityDao<T, Long> {
    List<T> findOrderByOrder();
}

OrderedEntity is a @MappedSuperclass entity.

But I'm getting exception when creating this bean:

Caused by: java.util.NoSuchElementException
    at java.util.ArrayList$Itr.next(ArrayList.java:854)
    at org.springframework.data.jpa.repository.query.ParameterMetadataProvider.next(ParameterMetadataProvider.java:121)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:274)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:180)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:109)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.create(JpaQueryCreator.java:49)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createCriteria(AbstractQueryCreator.java:109)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:88)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:73)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.<init>(PartTreeJpaQuery.java:118)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$CountQueryPreparer.<init>(PartTreeJpaQuery.java:241)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:68)

How to write this method correct?

Edit:

@MappedSuperclass
public abstract class OrderedEntity extends IdEntity implements Comparable<OrderedEntity> {
    @Nonnull
    @Column(name = "`order`")
    private Long order;
}

Upvotes: 5

Views: 6057

Answers (3)

xenteros
xenteros

Reputation: 15842

The correct named query will be:

public interface OrderedEntityDao<T extends OrderedEntity> extends EntityDao<T> {

    public List<T> findAllByOrderBy<colname><Desc|Asc>();

}

In your case:

public List<T> findAllByOrderByOrderDesc();
public List<T> findAllByOrderByOrderAsc();

Upvotes: 6

Parth Solanki
Parth Solanki

Reputation: 3448

I think this below code is work,

@NoRepositoryBean
public interface OrderedEntityDao<T extends OrderedEntity> extends EntityDao<T, Long> {
    List<T> findAllOrderByOrderAsc();
}

Upvotes: 3

rorschach
rorschach

Reputation: 2947

It should be

public List<T> findByOrder(Long order);

The correct syntax for query methods with Spring Data is basically findBy followed by the variable names, separated with And/Or. Refer to the full documentation here.

Upvotes: -1

Related Questions