2014-04-02 26 views
2

我必須閱讀hibernate中的一些特定列。我已經寫了這樣的方法在hibernate中讀取對象格式的特定列

Branch getBranch(long branchId) 
{ 
    String query = "select distinct bran.branch.branchId,bran.branch.branchName from Location bran where bran.branch.branchId =:branchId"; 
    Session session = getSession(); 
    session.beginTransaction(); 
    Query buildQuery = getSession().createQuery(query).setParameter("branchId", branchId); 
    List<Object[]> countryList = buildQuery.list(); 
    Branch branch = null; 
    for(Object[] obj : countryList) 
    { 
     branch = new Branch((Long)obj[0] , (String)obj[1]); 
    } 
    session.close(); 
    return branch; 
} 

但是在這裏,我必須手動構造我不想要的對象。我想讀取對象形式的結果,我不想手動構建對象。我的實體是這樣的

public final class Location implements Comparable<Location>{ 

    @Id 
    @Column(name = Tables.LOCATION.LOCATION_ID, nullable = false, precision = 15, scale = 0, updatable = false, insertable = false) 
    private long locationId; 

    @Column(name = Tables.LOCATION.LOCATION_NAME, length = 60, updatable = false, insertable = false) 
    private String locationName; 

    @Embedded 
    private Country country; 

    @Embedded 
    private Branch branch; 

分支不映射到實體,而它是可嵌入的。我想以DTO的形式讀取數據,所以我已經通過了ResultTransformer類,但它只能用sqlQuery而不是HQL(如果我錯了,請更正)。我不能改變我的查詢。請幫我

回答

1

Hibernate可以爲你做這個通過使用HQL的new關鍵字(called dynamic instantiation/constructor expression):

查詢只需更改爲:

select new your.package.name.Branch(bran.branch.branchId,bran.branch.branchName) from Location bran where bran.branch.branchId =:branchId 
+1

感謝亞歷山大。 。它工作正常,但讓我知道package.className始終是必需的,即使當我從同一個包調用它因爲已經嘗試過這種方式之前,它不工作時,我只使用類名。 – rishi