且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JPA查询方法从表中选择两列的所有数据

更新时间:2023-08-26 13:51:10

首先创建一个结果类:

  package com.example; 

public class ResultClass {

private Long id;
私人字符串名称;

public ResultCalss(Long id,String name){
// set
}
}
$ p

$ b

,然后使用自定义的@Query:
$ b $ pre $ @ $ c $ @从MyEntity e中选择新的com.example.ResultClass(e.id,e.name))
public List< ResultClass> findIdsAndNames();


I want to add in my Repository interface a method for a following SQL query:

SELECT ID, NAME  FROM TABLE_NAME

This SQL query works as expected, but I want to write it as a JPA query method, I've tried in many ways but didn't get it working, Please help me.

Following which I've tried but didn't work:

findAllByIdName(){}
findAllByIdAndName(){}
findByIdName(){}
findByIdAndName(){}

Create a result class first:

package com.example;

public class ResultClass{

  private Long id;
  private String name;

  public ResultCalss(Long id, String name){
     // set
  }
}

and then use a custom @Query:

@Query("select new com.example.ResultClass(e.id, e.name) from MyEntity e")
public List<ResultClass> findIdsAndNames();