2017-10-07 35 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查詢的方法。