将 OrderBy 与 JPARepository 一起使用

Posted

技术标签:

【中文标题】将 OrderBy 与 JPARepository 一起使用【英文标题】:Use OrderBy with JPARepository 【发布时间】:2018-09-19 23:19:50 【问题描述】:

我有这样的代码:

public interface BatchExecuteHistoryRepository extends JpaRepository<BatchExecuteHistory, Long> 
Page<BatchExecuteHistory> findByBatchExecuteHistoryIdBatchIdOrderByTimeEndAsc(String batchId, Pageable pageable);

这是我的数据库:

这是我在我的网站上得到的:

任何人都知道为什么查询不能使用 Order By time_end ASC 吗??? 我尝试了findByBatchExecuteHistoryIdBatchId(String batchId, Pageable pageable) 并得到了相同的结果

注意BatchExecuteHistoryId是一个复合id,batchId是它的一个元素

更新,这是我的 BatchExecuteHistory 类:

public class BatchExecuteHistory implements Serializable 

private static final long serialVersionUID = 1L;

@EmbeddedId
private BatchExecuteHistoryId batchExecuteHistoryId;

@NotNull
@Size(max = 100)
@Column(name = "batch_name", length = 100, nullable = false)
private String batchName;

@NotNull
@Column(name = "status", nullable = false)
private Boolean status;

@NotNull
@Column(name = "time_end", nullable = false)
private Instant timeEnd;

@Size(max = 100)
@Column(name = "error_step", length = 100)
private String errorStep;

@Size(max = 100)
@Column(name = "error_content", length = 100)
private String errorContent;

@Column(name = "row_input")
private Long rowInput;

public BatchExecuteHistoryId getBatchExecuteHistoryId() 
    return batchExecuteHistoryId;


public void setBatchExecuteHistoryId(BatchExecuteHistoryId batchExecuteHistoryId) 
    this.batchExecuteHistoryId = batchExecuteHistoryId;


public Boolean getStatus() 
    return status;


public String getBatchName() 
    return batchName;


public BatchExecuteHistory batchName(String batchName) 
    this.batchName = batchName;
    return this;


public void setBatchName(String batchName) 
    this.batchName = batchName;


public Boolean isStatus() 
    return status;


public BatchExecuteHistory status(Boolean status) 
    this.status = status;
    return this;


public void setStatus(Boolean status) 
    this.status = status;


public Instant getTimeEnd() 
    return timeEnd;


public BatchExecuteHistory timeEnd(Instant timeEnd) 
    this.timeEnd = timeEnd;
    return this;


public void setTimeEnd(Instant timeEnd) 
    this.timeEnd = timeEnd;


public String getErrorStep() 
    return errorStep;


public BatchExecuteHistory errorStep(String errorStep) 
    this.errorStep = errorStep;
    return this;


public void setErrorStep(String errorStep) 
    this.errorStep = errorStep;


public String getErrorContent() 
    return errorContent;


public BatchExecuteHistory errorContent(String errorContent) 
    this.errorContent = errorContent;
    return this;


public void setErrorContent(String errorContent) 
    this.errorContent = errorContent;


public Long getRowInput() 
    return rowInput;


public BatchExecuteHistory rowInput(Long rowInput) 
    this.rowInput = rowInput;
    return this;


public void setRowInput(Long rowInput) 
    this.rowInput = rowInput;


@Override
public int hashCode() 
    final int prime = 31;
    int result = 1;
    result = prime * result + ((batchExecuteHistoryId == null) ? 0 : batchExecuteHistoryId.hashCode());
    result = prime * result + ((batchName == null) ? 0 : batchName.hashCode());
    result = prime * result + ((errorContent == null) ? 0 : errorContent.hashCode());
    result = prime * result + ((errorStep == null) ? 0 : errorStep.hashCode());
    result = prime * result + ((rowInput == null) ? 0 : rowInput.hashCode());
    result = prime * result + ((status == null) ? 0 : status.hashCode());
    result = prime * result + ((timeEnd == null) ? 0 : timeEnd.hashCode());
    return result;


@Override
public boolean equals(Object obj) 
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    BatchExecuteHistory other = (BatchExecuteHistory) obj;
    if (batchExecuteHistoryId == null) 
        if (other.batchExecuteHistoryId != null)
            return false;
     else if (!batchExecuteHistoryId.equals(other.batchExecuteHistoryId))
        return false;
    if (batchName == null) 
        if (other.batchName != null)
            return false;
     else if (!batchName.equals(other.batchName))
        return false;
    if (errorContent == null) 
        if (other.errorContent != null)
            return false;
     else if (!errorContent.equals(other.errorContent))
        return false;
    if (errorStep == null) 
        if (other.errorStep != null)
            return false;
     else if (!errorStep.equals(other.errorStep))
        return false;
    if (rowInput == null) 
        if (other.rowInput != null)
            return false;
     else if (!rowInput.equals(other.rowInput))
        return false;
    if (status == null) 
        if (other.status != null)
            return false;
     else if (!status.equals(other.status))
        return false;
    if (timeEnd == null) 
        if (other.timeEnd != null)
            return false;
     else if (!timeEnd.equals(other.timeEnd))
        return false;
    return true;


@Override
public String toString() 
    return "BatchExecuteHistory [" + batchExecuteHistoryId.toString() + ", batchName=" + batchName + ", status="
            + status + ", timeEnd=" + timeEnd + ", errorStep=" + errorStep + ", errorContent=" + errorContent
            + ", rowInput=" + rowInput + "]";

【问题讨论】:

【参考方案1】:

你应该在OrderBy之前添加一个By,所以你的方法应该是:findByBatchExecuteHistoryIdBatchIdByOrderByTimeEndAsc

【讨论】:

也可以看看:***.com/questions/25486583/… 派生查询无效!未找到 String 类型的属性!遍历路径:BatchExecuteHistory.batchExecuteHistoryId.batchId.【参考方案2】:

我想你不会错过命名。见Spring document

订购方式

findByAgeOrderByLastnameDesc

... 其中 x.age = ?1 按 x.lastname desc 排序

它在我的环境中运行良好。我使用的是 2.6.0 版本。 我建议您检查 jpa 版本。我看不到您的 BatchExecuteHistoryId 类。

无论如何,试试看它是否在您的环境中运行良好。

数据库

CREATE TABLE MEMBER 
(
 id character varying(10),
 batch_id character varying(10),
 create_datetime timestamp without time zone NOT NULL,
 CONSTRAINT MEMBER_PK
 PRIMARY KEY (id,batch_id)
);
INSERT into MEMBER (id,create_datetime,batch_id) VALUES ('USER1','2021/11/20 14:00:00','1');
INSERT into MEMBER (id,create_datetime,batch_id) VALUES ('USER2','2021/11/15 14:00:00','1');
INSERT into MEMBER (id,create_datetime,batch_id) VALUES ('USER3','2021/11/10 14:00:00','1');

实体

@Entity(name = "Member")
@Table(name = "member")
@ToString
@Data
public class MemberEntity 

    @EmbeddedId
    private MemberPk batchExecuteHistoryId;
    
    @Column(name = "create_datetime")
    private LocalDateTime createDateTime;

实体的PK

@Embeddable
@ToString
public class MemberPk implements Serializable 
    
    private static final long serialVersionUID = 1L;
    
    private String id; 
    
    @Column(name = "batch_id")
    private String batchId;

存储库

@Repository
public interface MemberRepository extends JpaRepository<MemberEntity, String> 
    
    public List<MemberEntity> findByBatchExecuteHistoryIdBatchIdOrderByCreateDateTimeAsc(String batchId, Pageable pageable);


服务

@Service
public class MemberService 

    private final MemberRepository memberRepository;

    @Autowired
    public MemberService(MemberRepository memberRepository) 
        this.memberRepository = memberRepository;
    
    
    @PostConstruct
    public void findAllMember() 
        List<MemberEntity> memberEntitys = memberRepository.findAll();
        
        //MemberEntity(batchExecuteHistoryId=MemberPk(id=USER1, batchId=1), createDateTime=2021-11-20T14:00)
        //MemberEntity(batchExecuteHistoryId=MemberPk(id=USER2, batchId=1), createDateTime=2021-11-15T14:00)
        //MemberEntity(batchExecuteHistoryId=MemberPk(id=USER3, batchId=1), createDateTime=2021-11-10T14:00)
        memberEntitys.forEach(System.out::println); 
        
        System.out.println("----------------------------");
        
        //MemberEntity(batchExecuteHistoryId=MemberPk(id=USER3, batchId=1), createDateTime=2021-11-10T14:00)
        //MemberEntity(batchExecuteHistoryId=MemberPk(id=USER2, batchId=1), createDateTime=2021-11-15T14:00)
        List<MemberEntity> memberEntitysWithOrderBy = memberRepository.findByBatchExecuteHistoryIdBatchIdOrderByCreateDateTimeAsc("1",PageRequest.of(0, 2));
        
        memberEntitysWithOrderBy.forEach(System.out::println);
    

【讨论】:

以上是关于将 OrderBy 与 JPARepository 一起使用的主要内容,如果未能解决你的问题,请参考以下文章

将 @EmbeddedId 与 JpaRepository 一起使用

我应该如何将 JpaRepository.findOne() 与 SpringBoot 一起使用?

将 QuerydslPredicateExecutor 与 JpaRepository 一起使用时出现 IllegalAccessException

将 JpaRepository 与 Spring 数据和 Hibernate 一起使用

如何将 FindAllBy 与 JpaRepository 中的多个字段一起使用?

Spring Data JPA - JpaRepository 中的自定义排序