【问题标题】:how to get specific column in Spring JPA?如何在 Spring JPA 中获取特定列?
【发布时间】:2019-11-21 13:55:47
【问题描述】:

我可以通过 findAll() 从 db 获取以下数据

[
   { id : 1,
     name : "John",
     age : "23",
     sex : "male"
   },
   { id : 2
...

]


我想要做的是从 db 获取特定数据,如下所示。

[ 
   { id : 1,
     name : "John"
   },
   { id : : 1, 
     name : "Peter"
   }
...
]

所以我尝试了这样。

存储库

@Repository
public interface PersonDAO extends JpaRepository<Person, Integer> {

    @Query(value ="select p.id , p.name from person p", nativeQuery = true)
    Collection<Object> getPersonIdAndName();
}


控制器

@GetMapping ("/getPersonIdAndName")
    public Collection<Object> getPerson() {
        return personDAO.getPersonIdAndName();
    }


但结果是这样的(邮递员)

[
    [
        1,
        "John"
    ],
    [
        2,
        "Peter"
    ]
....
]


我想要一个类型key : value,而不仅仅是值,
因为我想把它提取到 React.js 状态。
我该如何解决? 感谢您的帮助

【问题讨论】:

标签: spring jpa repository


【解决方案1】:

您需要使用投影。创建一个新界面

public interface PersonProjection {

    Integer getId();

    String getName();

}

之后在你的存储库中使用返回类型中的投影

@Repository
public interface PersonDAO extends JpaRepository<Person, Integer> {

    @RestResource(exported = false)
    Query("select p.id, p.name from Person as p")
    Collection<PersonProjection> getPersonIdAndName();
}

或者,如果您想@Override findAll() 方法,您可以创建一个自定义存储库。这里有一个 GitHub repo 示例https://github.com/federicogatti/Spring-Custom-Repository-Example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-27
    • 2022-07-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多