How to select all the data of two columns from a table using JPA query method

Viewed 17536

I want to add in my Repository interface a method for the 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(){}
3 Answers

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();

Just use interface- or class-based projections:

public interface IdAndName {
    Long getId();
    String getName();
}

public interface MyRepo extends CrudRepository<MyEntity, Long> {
    List<IdAndName> findBy();
}

More info.

I have similar implementation. Custom query required to achieve this.

e.g -

@Query("SELECT usr.id, usr.name FROM User usr")
public List<User> findIdsAndNames();

And the User class is

@Entity
@Table(name="t_user")
public class User{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id", nullable = false)
    private Long id;

    @Column(name="name")
    private String name;
............
}
Related