我有一个包含两个表的数据库:
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是与第一个表的关系。 我想通过第一个查询来提取 表,按文章描述排序的文章。 我不知道该怎么做,我从这个查询开始:
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("SELECT * FROM number n join article a on n.id = a.numbers_id order by a.id ")
关于java - Spring存储库查询两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46619496/