Spring Boot : Using JPA want to get the unique value from table

喜欢而已 提交于 2021-01-29 13:29:09

问题


I have a table

CatID | CategoryName | scatID | subCategoryName 2 User 1 x 2 User 2 y 2 User 3 z 2 User 4 a 2 User 5 b

I am able to get all the value in JSON formate using SpringBoot.

My Requirement : I want to get the unique CategoryName attribute but in current scenario I am getting all User coming 5 times.

I am looking for solution. Please any one can help to get over using Spring Boot JPA implementation.


回答1:


You can use the Query annotation in your repository interface. For example, below snippet code return all distinct categoryName.

Declare a simple bean class:

package com.example.test;

public class CategoryNameClass {
    private String CategoryName;

    public CategoryNameClass(String CategoryName) {
        this.CategoryName = CategoryName;
    }

    public String getCategoryName() {
        return CategoryName;
    }

    public void setCategoryName(String categoryName) {
        CategoryName = categoryName;
    }
}

Then use the below query:

public interface ARepo extends JpaRepository<A, String> {

    @Query("SELECT DISTINCT new com.example.test.CategoryNameClass(a.categoryName) FROM A a ")
    List<CategoryNameClass> findAllCategoryName();
}


来源:https://stackoverflow.com/questions/61089428/spring-boot-using-jpa-want-to-get-the-unique-value-from-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!