添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
豪情万千的回锅肉  ·  旺旺 ...·  1 周前    · 
酷酷的毛巾  ·  app clear ...·  1 月前    · 
路过的茴香  ·  VSTO ...·  1 月前    · 
腼腆的牛肉面  ·  import java.io.; ...·  1 月前    · 
神勇威武的红酒  ·  Feign Client without ...·  2 月前    · 
活泼的椅子  ·  Oracle - 子查询、TOP - N ...·  1 年前    · 
有情有义的匕首  ·  VBA ...·  1 年前    · 

Spring JPA Group By,联合主键(多主键)

项目 是Spring boot,想要使用Spring JPA实现Group By 功能,但是Spring支持的查询关键字不包括Group By,只能另辟蹊径了。



表结构:


​ 最上面三个字段组成联合主键。


想要实现的SQL功能:

(select中的参数必须满足上面的三个联合主键,不能少)

SELECT max(trade_date), max(class_type),  cat_id 
FROM cs_index_pe_ratio_industry
group by cat_id


创建定制方法接口:

public interface CsIndexPeRatioIndustryRepositoryMy {
    List<CsIndexPeRatioIndustry> findAllByIdTradeDate();
}


实现类:

public class CsIndexPeRatioIndustryRepositoryMyImpl implements CsIndexPeRatioIndustryRepositoryMy {
	@PersistenceContext
	private EntityManager entityManager;
	public void setEntityManager(EntityManager em) {
		this.entityManager = em;
	@Override
	public List<CsIndexPeRatioIndustry> findAllByIdTradeDate() {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<CsIndexPeRatioIndustry> query = criteriaBuilder.createQuery(CsIndexPeRatioIndustry.class);
		Root<CsIndexPeRatioIndustry> root = query.from(CsIndexPeRatioIndustry.class);
		query.multiselect(criteriaBuilder.max(root.get("id").get("tradeDate")), criteriaBuilder.max(root.get("id").get("classType")), root.get("id").get("catId"))
				.groupBy(root.get("id").get("catId"));
		return entityManager.createQuery(query).getResultList();
} 


注意 query.multiselect 中参数的排列顺序。

创建主Repository:

public interface CsIndexPeRatioIndustryRepository extends JpaRepository<CsIndexPeRatioIndustry, String>, CsIndexPeRatioIndustryRepositoryMy {
} 


使用方法:

@Autowired
CsIndexPeRatioIndustryRepository csIndexPeRatioIndustryRepository;
。。。。。。。。。。。。。。。。。
。。。。。。。。。。。。。。。。。
。。。。。。。。。。。。。。。。。
List<CsIndexPeRatioIndustry> findAllByIdTradeDate = csIndexPeRatioIndustryRepository.findAllByIdTradeDate();
 



最重要的是POJO类怎么写:

一定要注意构造方法里面的参数顺序,一定要跟上面的query.multiselect中的参数顺序一致。

public class CsIndexPeRatioIndustry {
    public CsIndexPeRatioIndustry() {
	public CsIndexPeRatioIndustry(String tradeDate, String classType, String catId) {
		this.id = new CsIndexPeRatioIndustryId();
		this.id.setTradeDate(tradeDate);
		this.id.setClassType(classType);
		this.id.setCatId(catId);
	@EmbeddedId
	protected CsIndexPeRatioIndustryId id;
    protected String level; 
    protected String parentCid; 
    protected String industryName; 
    protected String industryNameEn;
    protected String industryCode; 
} 


@Embeddable
public class CsIndexPeRatioIndustryId implements Serializable{
	public CsIndexPeRatioIndustryId() {