Spring JPA getting a Projection from an Entity with a Query

Multi tool use


Spring JPA getting a Projection from an Entity with a Query
In my application I have a Hero Entity. I also want to be able to return a list of each hero id and name. I got it working with this:
@Repository
public interface HeroEntityRepository extends JpaRepository<HeroEntity, Long> {
@Query("select s.id, s.name from HEROES s")
List<Object> getIdAndName();
}
// in controller:
@GetMapping
public List<Object> getHeroNames() {
return heroEntityRepository.getIdAndName();
}
I tried the suggestion in another post to substitute the Object with a Interface, but then I receive a list of null values ( [{"name":null,"id":null},{"name":null,"id":null}, // etc ).
The custom Interface:
public interface HeroNameAndId {
Long getId();
String getName();
}
When making a Entity with only id and name values I received a 'ConverterNotFoundException'. Im not sure what the right way to go is. I have it working with Object but this doesn't seem very clean.
My HeroEntity:
@Getter
@Builder
@Entity(name = "HEROES")
@AllArgsConstructor
public class HeroEntity extends HasId<Long> {
private String name;
private String shortName;
private String attributeId;
@ElementCollection private List<String> translations;
@OneToOne(cascade = CascadeType.ALL) private HeroIconEntity icon;
private String role;
private String type;
private String releaseDate;
@OneToMany(cascade = CascadeType.ALL) private List<AbilityEntity> abilities;
@OneToMany(cascade = CascadeType.ALL) private List<TalentEntity> talents;
}
@MappedSuperclass
public abstract class HasId<T> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Setter
@Getter
private T id;
}
No, I only substituted the Object for HeroNameAndId Interface in the methods (eg. List<HeroNameAndId> getHeroNames() ).
– Bowerick
32 mins ago
you have to change your repository method from
List<Object> getIdAndName();
to Collection<HeroNameAndId> getIdAndName();
– pvpkiran
29 mins ago
List<Object> getIdAndName();
Collection<HeroNameAndId> getIdAndName();
1 Answer
1
You must use field aliases to make @Query with projection work:
@Query("select s.id as id, s.name as name from HEROES s")
The aliases must match the names in your HeroNameAndId interface.
Works like a charm! Thank you!
– Bowerick
13 mins ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
after you introduced Interface(it is called Projection). Did you change your Repository method in any way? if so waht did u change?
– pvpkiran
45 mins ago