2017-10-07 61 views
0

我有两个表的数据库:春库查询两个表

1)NumberEntity

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

2)ArticleEntity

|------|-------|------------| 
| 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; 

所以我需要这样一个查询(即使itsn't纠正,但它只能是伪代码):

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

的问题是,我不知道如何加入其他表用使用弹簧的单个查询

+0

https://stackoverflow.com/questions/43891571/crudrepository-join-single-field-from-other-table-to-entity-as-readonly.please检查此链接。 – Ram

回答

1

您可以使用查询。尝试此代码。

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

谢谢,但查询发起异常。我需要传递两个参数:音量和数字。你能帮助我更好吗?使用Spring JPA查询有没有一种方法? – Pocho

+0

你太棒了!我解决了你的意见,你的解决方案接近我的请求︰@Query(value =“SELECT a。* FROM numberentity n INNER JOIN articleentity a on n.id =(select n.id from numberentity n where n.volume =?1 AND n.numero =?2)AND n.id = a.numbers_id order by a。文章asc“,nativeQuery = true) – Pocho

0
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。

+0

我没有使用会话 – Pocho

+0

您可以通过@PersistanceContext将entityManager注入到存储库,然后该查询将起作用。 –

0

首先尝试不创建双向关系,因为当你做出选择时你将面临一个循环;在你的情况下,从文章到数字创建一个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由article.number.volume或什么后,你想...

也请阅读约Criteria。这种编写查询的方法要简单得多,因为它有一些实现大量SQL查询的方法。