需求
现在有一张article
表,用来储存文章,对应的实体类如下:
package com.qianyucc.blog.model;
import lombok.*;
import javax.persistence.*;
/**
* @author lijing
* @date 2019-08-05 14:28
* @description 文章
*/
@Data
@Entity
@Table(name = "article")
public class Article {
@Id
// 主键自增
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "author",unique = false,nullable = false,length = 20)
private String author;
@Column(name = "title",length = 100)
private String title;
@Column(name = "content",columnDefinition = "clob not null")
private String content;
@Column(name = "tags",length = 50)
private String tags;
@Column(name = "type")
private Integer type;
@Column(name = "categories",length = 50)
private String categories;
@Column(name = "gmt_create")
private Long gmtCreate;
@Column(name = "gmt_update")
private Long gmtUpdate;
@Column(name = "tabloid")
private String tabloid;
@Column(name = "likes")
private Integer likes;
@Column(name = "views")
private Integer views;
}
现在需要查询文章的所有分类,也就是categories
属性
解决方法
网上的一些方法分别是重写构造器、或者自定义接口作为返回类型,但是我试了后都不能很好的解决问题。下面提供一种方法,亲测可以实现上面的需求。
一个字段的情况
- Controler:
package com.qianyucc.blog.controller;
/**
* @author lijing
* @date 2019-08-05 15:13
* @description
*/
@RestController
public class ArticleController {
@Autowired
private ArticleRepositoryarticleRepository;
@GetMapping("/getAllCategories")
public Object getAllCategories(){
return articleRepository.getAllCategories();
}
}
- Repository:(这里省略Service层)
package com.qianyucc.blog.repository;
import com.qianyucc.blog.model.*;
import org.springframework.data.jpa.repository.*;
import java.util.*;
/**
* @author lijing
* @date 2019-08-05 14:28
* @description 文章数据库访问层
*/
public interface ArticleRepository extends JpaRepository<Article,Long>,JpaSpecificationExecutor<Article> {
@Query(value = "select distinct categories from article",nativeQuery = true)
// 这里注意返回值用String类型接收
List<String> findAllCategories();
}
上面的nativeQuery属性设置为true的时候可以使用SQL语句。
- 测试结果:
- 控制台打印:
多个字段的情况
- 只需修改Repository,注意现在的返回值为
List<Map<String,Object>>
public interface ArticleRepository extends JpaRepository<Article,Long>,JpaSpecificationExecutor<Article> {
@Query(value = "select author,categories from article",nativeQuery = true)
List<Map<String,Object>> findAllCategories();
}
- 测试结果
- 控制台打印