在Spring Data中查找按字段排序的所有实体的正确方法是什么?

时间:2016-09-24 05:48:31

标签: java spring spring-data

我使用的是Spring Data JPA,并希望在我的基础Repository界面中添加一个方法,以便按字段order排序所有实体:

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

OrderedEntity@MappedSuperclass实体。

但是我在创建这个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)

如何正确编写此方法?

修改

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

3 个答案:

答案 0 :(得分:4)

正确的命名查询将是:

outer

在你的情况下:

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

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

}

答案 1 :(得分:2)

我认为以下代码是可行的,

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

答案 2 :(得分:-1)

应该是

public List<T> findByOrder(Long order);

使用Spring Data的查询方法的正确语法基本上是findBy,后跟变量名称,用And / Or分隔。请参阅完整文档here