繁体   English   中英

带有两个表的 Spring 存储库查询

[英]Spring repository query with two table

我有一个包含两个表的数据库:

1) 号码实体

|------|-------|--------|
|  id  |numero | volume |
|------|-------|--------|
|  1   |    1  |   1    |
|------|-------|--------|
|  2   |    1  |   2    |
|------|-------|--------|
|  3   |    2  |   1    |
|------|-------|--------|

2) 文章实体

|------|-------|------------|
|  id  |Article| numbers_id |
|------|-------|------------|
|  5   |    7  |   1        |
|------|-------|------------|
|  6   |    5  |   2        |
|------|-------|------------|
|  7   |    6  |   3        |
|------|-------|------------|

其中 numbers_id 是与第一个表的关系。 我想通过第一个表查询提取按文章 desc 排序的文章。 我不知道我该怎么做,我从这个查询开始:

public List<NumberEntity> findByVolumeAndNumero(String volume, String number);

我得到了文章列表,但第一个是文章编号 7,相反,我想像第一篇文章一样提取编号 5、6 和 7。

这些是我的模型:

    @Entity
    public class NumberEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String volume;
    private String numero;
    @OneToMany(mappedBy="numbers", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ArticleEntity> articles = new ArrayList<ArticleEntity>();

另一个:

 @Entity
    public class ArticleEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String article;
    @ManyToOne
    private NumberEntity numbers;

所以我需要一个这样的查询(即使它不正确,但它只是伪代码):

public List<NumberEntity> findByVolumeAndNumeroOrderByArticleDesc(String volume, String number);

问题是,我不明白如何使用 Spring 通过单个查询连接另一个表

您可以使用Query来做到这一点。试试这个代码。

 @Query("SELECT * FROM number n join article a on n.id = a.numbers_id order by a.id  ")

首先尽量不要创建双向关系,因为当您进行选择时,您将面临一个循环; 在你的情况下,从文章到数字创建一个 ManyToOne 关系就足够了。 查询应如下所示:

@Query("select * from ArticleEntity article inner join article.numbers number where article.numbers.volume=:volume and article.numbers.id=:id")
    List<ArticleEntity> findAll(@Param("volume") String volume , @Param("id") long id);

试试这个查询(ps检查字段的名称是否与它们在java类(实体)中的名称相同)

在您可以通过文章.编号.数量或您想要的内容添加到您的查询订单desc之后...

另请阅读Criteria 这种编写查询的方式要简单得多,因为有一些方法可以实现很多 SQL 查询。

entityManager.createQuery("SELECT ae FROM ArticleEntity ae WHERE ae.numbers.volume = :volume AND ae.numbers.numero = :numero ORDER BY ae.article DESC).setParameter("volume", volume).setParameter("numero", numero)

如果您正在使用会话,您可以与它交换 entityManager。

@Query("SELECT a FROM ArticleEntity a, NumberEntity n WHERE ...")

暂无
暂无

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

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