hibernate native sql的小技巧
為了性能考慮,使用了
native sql
。因為需要分頁,需要
2
個
sql
,一個獲取
list
一個取得總數。獲取
list
很好寫:
?
?1
private
?List?getListByNativeSQL(
final
?Class?cls,?
final
?String?sql)?
{
?2
?3
???????
return
?(List)?getHibernateTemplate().execute(
new
?HibernateCallback()?
{
?4
?5
???????????
public
?Object?doInHibernate(Session?session)
?6
?7
??????????????????
throws
?HibernateException?
{
?8
?9
??????????????
return
?session.createSQLQuery(sql).addEntity(cls).list();
10
11
???????????}
12
13
???????}
);
14
15
????}
16



?2

?3



?4

?5

?6

?7



?8

?9

10

11

12

13

14

15

16

?
獲取總數查了下
hibernate
的
reference,
試了幾次才明白用法
:
?1
private
?BigInteger?getCountByNativeSQL(
final
?String?sql)?
{
?2
?3
???????
return
?(BigInteger)?getHibernateTemplate().execute(
?4
?5
??????????????
new
?HibernateCallback()?
{
?6
?7
??????????????????
public
?Object?doInHibernate(Session?session)
?8
?9
?????????????????????????
throws
?HibernateException?
{
10
11
?????????????????????
return
?(BigInteger)?(session.createSQLQuery(sql).uniqueResult());
12
13
??????????????????}
14
15
??????????????}
);
16
17
????}
18



?2

?3

?4

?5



?6

?7

?8

?9



10

11

12

13

14

15

16

17

18

這里的
sql 是“ select count(*) 開頭的”。這里大家可能要問,為什么要使用 BigInteger ,因為如果用 uniqueResult() 默認就返回 BigInteger ,而 BigInteger cast 成 Integer 會出錯。那么如果我就是要返回 Integer 呢,可以通過下面的辦法實現:
?1
private
?Integer?getCountByNativeSQL(
final
?String?sql)?
{
?2
?3
???????
return
?(Integer)?getHibernateTemplate().execute(
?4
?5
??????????????
new
?HibernateCallback()?
{
?6
?7
??????????????????
public
?Object?doInHibernate(Session?session)
?8
?9
?????????????????????????
throws
?HibernateException?
{
10
11
?????????????????????
return
?(Integer)?(session.createSQLQuery(sql).addScalar(
"
count
"
,?Hibernate.INTEGER).uniqueResult());
12
13
??????????????????}
14
15
??????????????}
);
16
17
????}
18



?2

?3

?4

?5



?6

?7

?8

?9



10

11

12

13

14

15

16

17

18

大家注意粗體的部分,這里是給一個
alias 賦予類型,那么 sql 就需要變成以 ”select count(*) as count ” 開頭了。posted on 2007-03-02 10:52 pesome 閱讀(5261) 評論(2) 編輯 收藏 所屬分類: 開源軟件