【发布时间】:2018-07-21 17:14:43
【问题描述】:
我在 Spring Java JPA 中有以下实体:
@Entity
@Table(name = "todo")
public class TodoEntity {
@Id
@GeneratedValue
private Long id;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Long userId;
private String text;
private String description;
private Boolean expanded;
private Boolean completed;
private Integer sortOrder;
private Date expiredDate;
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
private Integer priority;
private Long parentId;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "parentId", referencedColumnName = "id")
private Set<TodoEntity> children;
.....getter and setter
}
现在我的问题是孩子的分类。 我想有时按日期对它们进行排序,有时按 sortOrder(所以基本上使用不同的参数)。
如何在 JPA 中做到这一点?
信息:
- 使用 Spring JPA 数据存储库
存储库:
@Repository
public interface TodoRepository extends JpaRepository<TodoEntity, Long> {
Page<TodoEntity> findByUserIdAndParentIdAndTextContaining(Long userId, Long parentId, String text, Pageable pageable);
Page<TodoEntity> findByUserIdAndParentId(Long userId, Long parentId, Pageable pageable);
TodoEntity findByUserIdAndId(Long userId, Long id);
}
我们以 findByUserIdAndParentId 为例
【问题讨论】:
-
你在使用 spring-data 存储库吗?
-
是的。使用 JPARepostiory
-
显示您的存储库,可能是您想要排序的查询方法
-
试试
findByUserIdAndIdOrderByChildern_SortOrder(Long userId, Long id); -
不,不幸的是,这不起作用。也许也让它更清楚。我希望所有孩子都得到正确分类。现在 OneToMany 中的孩子是随机排序的。我希望他们按 sortOrder 或 creationDate 或 updateDate 排序
标签: java spring hibernate spring-data-jpa jpql