omickron omickron - 2 months ago 30
Java Question

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?

===== update

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

@Override
public int compareTo( OrderedEntity o ) {
return new CompareToBuilder().append( order, o.order ).build();
}
}


@MappedSuperclass
@Getter
@Setter
public abstract class IdEntity extends ValidatedRequest implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Version
private Long version;

@Override
public boolean equals( Object obj ) {
if (!(obj instanceof IdEntity)) {
return false;
}
IdEntity entity = (IdEntity) obj;
return new EqualsBuilder().append( id, entity.getId() ).isEquals();
}

@Override
public int hashCode() {
return new HashCodeBuilder().append( id ).build();
}
}

Answer

The correct named query will be:

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

In your case:

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