微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

附加表@ManytoMany上的JPA存储库查询

如何解决附加表@ManytoMany上的JPA存储库查询

我想在我的jpa spring存储库中做这样的选择

SELECT  sicknes_id,count(symptomp_id) as ilosc FROM symptomp_sicknes where symptomp_id IN (1,2) group by sicknes_id Order by  ilosc DESC;

我的实体

@Entity
@Table(name = "symptomp")
public class Symptomp {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "symptomp_id")
    private Long symptomp_id;
    @Column(name = "name")
    private String name;
    @Column(name = "description")
    private String description;
    @ManyToMany(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},fetch = FetchType.LAZY)
    @JoinTable(name = "symptomp_sicknes",joinColumns = @JoinColumn(name = "symptomp_id"),inverseJoinColumns = @JoinColumn(name = "sicknes_id"))
    private Set<Sicknes> sicknes = new HashSet<>();


@Entity
@Table(name = "sicknes")
public class Sicknes {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "sicknes_id")
    private Long sicknes_id;
    @Column(name = "name")
    private String name;
    @Column(name = "description")
    private  String description;
    @ManyToOne(cascade = {CascadeType.DETACH,fetch = FetchType.LAZY)
    @JoinColumn(name = "speciesId")
    private Species species;

 

我的Symptomp存储库:


public interface SymptompRepository extends JpaRepository<Symptomp,Long> {

    @Query("select p from Symptomp p where name like ?1%")
    public List<Symptomp> findAllBySymptompName(String symptomp);

    public Symptomp findByName(String symptomp);


    public List<Symptomp> findByNameIn(List<String> list);


    Integer countdistinctSymptompByName(String id);

}

如何在JPA存储库中创建此选择? 我尝试在select中获得价值,但我得到了错误映射bean。

解决方法

您可以使用nativeQuery=true参数将查询结果作为@Query("SELECT sicknes_id,count(symptomp_id) as ilosc FROM symptomp_sicknes where symptomp_id IN (1,2) group by sicknes_id Order by ilosc DESC",nativeQuery=true) List<Object[]> getQueryResult();

dto

其他选择是使用适当的构造函数创建public class QueryResultDto { Long sicknesId; Long count; public QueryResultDto(Long sicknesId,Long count) { this.sicknesId = sicknesId; this.count = count; } }

@Query("select new yourproject.dtopath.QueryResultDto(...")
List<QueryResultDto> getQueryResult(@Param("symptompIds") List<Long> symptompIds);

然后使用JPQL

{{1}}
,

如果要避免本机查询,最好的方法是为该JoinTable创建一个实体。然后,您可以轻松查询它。如果这样做的另一个好处是,如果将来会弹出一个要求,您必须在该关系中存储其他属性,则实体已经可以轻松地做到这一点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。