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;
}
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.