Bow*_*ick 3 java spring jpql spring-data-jpa
在我的应用程序中,我有一个英雄实体。我还希望能够返回每个英雄ID和名称的列表。我得到它与此工作:
@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();
}
Run Code Online (Sandbox Code Playgroud)
我在另一篇文章中尝试了用接口替换Object的建议,但是随后我收到了一个空值列表([{{name“:null,” id“:null},{” name“:null,” id“ :null},//等)。自定义界面:
public interface HeroNameAndId {
Long getId();
String getName();
}
Run Code Online (Sandbox Code Playgroud)
当创建仅具有ID和名称值的Entity时,我收到了“ ConverterNotFoundException”。我不确定正确的方法是。我有它与对象一起工作,但这似乎不是很干净。
我的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;
}
Run Code Online (Sandbox Code Playgroud)
您必须使用字段别名来使@Query与投影一起工作:
@Query("select s.id as id, s.name as name from HEROES s")
Run Code Online (Sandbox Code Playgroud)
别名必须与HeroNameAndId接口中的名称匹配。
| 归档时间: |
|
| 查看次数: |
1477 次 |
| 最近记录: |