2013-07-28 43 views
22

比方說,我有一個表,其中有兩列firstnamelastname與字符串數據類型。通常我寫我的hql查詢如我們可以連接Hibernate HQL查詢中的兩個屬性嗎?

"select firstname,lastname from contact" 

我可以編寫一個連接兩個屬性的hql查詢嗎?

也許像"select firstname+lastname as fullname from Contact"

回答

33
select concat(c.firstname, c.lastname) as fullname from Contact c 

或者,如果你想要一個分隔符:

select concat(c.firstname, ' ', c.lastname) as fullname from Contact c 

the documentation

+0

謝謝。是否可以在兩者之間添加'',''或'space'? – abiieez

+2

看到我編輯的答案。 –

3

我做到了,所以用HQL

public List<Contract> findContracts(String fullName) { 
    Query q = sessionFactory.getCurrentSession().createQuery("from Contract c where :fullName = concat(c.firstname, ' ', c.lastname)"); 
    q.setString("fullName", fullName); 
    return q.list();} 
15

你可以在你的實體創建一個計算列:

@Formula(value = " concat(first_name, ' ', last_name) ") 
private String fullName; 

而在你的HQL你只是指這個領域,你會做任何其他。

在你的情況,你可以這樣做:

"select fullName from Contact" 
2

您還可以使用||連接運算符:

"select c.firstName || ' ' || c.lastName as fullName from Contact" 

allthough它可能會令人困惑的閱讀。