Spring Data JPA 从带有查询的实体获取投影
Spring Data JPA getting a Projection from an Entity with a Query
在我的应用程序中,我有一个英雄实体。我还希望能够 return 列出每个英雄的 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();
}
我尝试了另一个 post 中的建议,用接口替换对象,但随后我收到一个空值列表([{"name":null,"id": null},{"name":null,"id":null}, // 等)。
自定义界面:
public interface HeroNameAndId {
Long getId();
String getName();
}
当创建一个只有 id 和 name 值的实体时,我收到了 'ConverterNotFoundException'。我不确定正确的方法是什么。我让它与 Object 一起工作,但这看起来不是很干净。
我的英雄实体:
@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;
}
您必须使用字段别名才能使@Query 具有投影功能:
@Query("select s.id as id, s.name as name from HEROES s")
别名必须与您的 HeroNameAndId 接口中的名称匹配。
在我的应用程序中,我有一个英雄实体。我还希望能够 return 列出每个英雄的 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();
}
我尝试了另一个 post 中的建议,用接口替换对象,但随后我收到一个空值列表([{"name":null,"id": null},{"name":null,"id":null}, // 等)。 自定义界面:
public interface HeroNameAndId {
Long getId();
String getName();
}
当创建一个只有 id 和 name 值的实体时,我收到了 'ConverterNotFoundException'。我不确定正确的方法是什么。我让它与 Object 一起工作,但这看起来不是很干净。
我的英雄实体:
@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;
}
您必须使用字段别名才能使@Query 具有投影功能:
@Query("select s.id as id, s.name as name from HEROES s")
别名必须与您的 HeroNameAndId 接口中的名称匹配。