简体   繁体   English

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

[英]Spring Data 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. 我还希望能够返回每个英雄ID和名称的列表。 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 ). 我在另一篇文章中尝试了用接口替换Object的建议,但后来我收到了一个空值列表([{“name”:null,“id”:null},{“name”:null,“id” :null},//等)。 The custom Interface: 自定义界面:

public interface HeroNameAndId {

    Long getId();
    String getName();
}

When making a Entity with only id and name values I received a 'ConverterNotFoundException'. 在创建仅具有id和name值的Entity时,我收到了“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:

@Query("select s.id as id, s.name as name from HEROES s")

The aliases must match the names in your HeroNameAndId interface. 别名必须与HeroNameAndId界面中的名称匹配。

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

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