2013-06-18 69 views
0

我有一些模型與它們之間的依賴關係。下面是型號:由Hibernate和JPA加入並加入組合

@Entity 
public class A extends Model { 
    @Required 
    public String name; 

    @Required 
    @ManyToOne(fetch = FetchType.LAZY) 
    public C modelC; 
} 

@Entity 
public class B extends Model { 
    @Required 
    public String name; 
} 

@Entity 
public class C extends Model { 
    @Required 
    public Date lastUpdate; 

    @Required 
    @OneToMany(mappedBy = "modelC", fetch = FetchType.LAZY, cascade = CascadeType.ALL) 
    public List<A> modelsA; 

    @Required 
    @ManyToOne(fetch = FetchType.LAZY) 
    public B modelB; 
} 

正如你可以看到名爲C模型包含幾種型號命名爲A和命名B一個模型。

我想要做的是選擇具有鮮明的模型B(由不同的id)所有車型C,並具有最大date(接近當前日期)。此外,我想選擇模型C(列表A和模型B)的依賴關係。

我有查詢加載所有車型C和它的依賴:

select distinct c from C c 
left join fetch c.modelsA 
left join fecth c.modelB 

我想我只能檢索的不同車型C(不同的模型B的ID)和與此查詢它的依賴:

select distinct c from C c 
left join fetch c.modelsA 
left join fetch c.modelB b 
group by b.id 

但是,如何檢索具有最高日期的不同型號C?這是行不通的:

select distinct c, max(c.lastUpdate) as maxUpdate from C c 
left join fetch c.modelsA 
left join fetch c.modelB b 
group by b.id 

你能幫我嗎?

下面是數據的一個例子:

B(b1): 
    name: First model of type B 

B(b2): 
    name: Second model of type B 

C(c1): 
    lastUpdate: 100 
    modelB: b1 

C(c2): 
    lastUpdate: 200 
    modelB: b2 

C(c3): 
    lastUpdate: 300 
    modelB: b1 

A(a1): 
    name: A1 
    modelC: c1 

A(a2): 
    name: A2 
    modelC: c1 

A(a3): 
    name: A3 
    modelC: c2 

A(a4): 
    name: A4 
    modelC: c3 

我想檢索該c2c3和它們的依賴。

謝謝您的幫助

回答

0

您可以使用ORDER BY,而且與HQL你沒有義務這樣做左連接,連接是太的Valide,becareful爲獲取利用率。

MAX(modelC.lastUpdate)也許嘗試這樣或c.modelC.lastUpdate

例如

query = "select u from User u " 
+ "left join u.linkedAccounts linkedAccounts " 
+ "where u.active = true " 
    + "and **linkedAccounts.providerKey** = :pProviderKey"),