Home > Net >  Select field from table with @Query using Spring Boot JPARepository
Select field from table with @Query using Spring Boot JPARepository

Time:11-03

Is it possible to select one or more fields from a table and map it into the entity?

Currently trying

@Repository
public interface RoleRepo extends JpaRepository<Role, Long>{  
    @Query("SELECT r.roleId, r.name FROM role r")  
    List<Role> getAllRoleNames();
}

I only want those 2 values and the rest of the fields can be null to make it more efficient. The error I get right now is

ConversionFailedException: Failed to convert from type [java.lang.Object[]] to type 
[@org.springframework.data.jpa.repository.Query demo.model.Role] for value '{1, Java Dev}'; 
nested exception is org.springframework.core.convert.ConverterNotFoundException: 
No converter found capable of converting from type [java.lang.Long] to type 
[@org.springframework.data.jpa.repository.Query demo.model.Role]] with root cause

So how can I make the conversion happen when I can't just say object.Id = role.roleId (object.Id would be that 1).

CodePudding user response:

WIth Spring Data you can use projections to accomplish this.

@Entity
public class ExampleEntity {
 
    @Id
    private Long id;
 
    @OneToOne
    private Person person;

    private String name;

    // getters and setters
}

.

public interface ExampleProjection {
    String getName(); // This must be exactly the same as your entity
}

Now you can use ExampleProjection in your Repository, even though the repository references the ExampleEntity and not the Projection.

public interface ExampleRepository extends Repository<ExampleEntity, Long> {
    List<ExampleProjection> findBy();
}

More information here: https://www.baeldung.com/spring-data-jpa-projections

CodePudding user response:

In Spring, you can use a custom entity as below :

NewRole.java

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class NewRole implements Serializable {

private static final long serialVersionUID = 1L;
@Id
private Long id;
private String name;

}

RoleRepo.java

@Repository
public interface RoleRepo extends JpaRepository<Role, Long> {  

@Query("SELECT new NewRole(r.id, r.name) FROM role r")  
List<NewRole> getAllRoleNames();

}

Good luck !

  • Related