繁体   English   中英

Spring Data JPA从具有查询的实体获取投影

[英]Spring Data JPA getting a Projection from an Entity with a Query

在我的应用程序中,我有一个英雄实体。 我还希望能够返回每个英雄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();
}

我在另一篇文章中尝试了用接口替换Object的建议,但后来我收到了一个空值列表([{“name”:null,“id”:null},{“name”:null,“id” :null},//等)。 自定义界面:

public interface HeroNameAndId {

    Long getId();
    String getName();
}

在创建仅具有id和name值的Entity时,我收到了“ConverterNotFoundException”。 我不确定正确的方法是什么。 我有它使用对象,但这似乎不是很干净。

我的英雄实体:

@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界面中的名称匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM