Hibernate或HQL选择另一个SELECT的结果

时间:2017-11-22 03:28:01

标签: java mysql hibernate hql

在以下查询中是否有使用HQL的方法?

SELECT userId, pwd, pwdDate FROM (SELECT userId, AES_DECRYPT(pwd, 'key_str') as pwd, pwdDate FROM UserHistory order by pwdDate desc limit 5 ) AS A WHERE pwd = :pwd

以下工作。

SELECT * FROM UserHistory order by pwdDate desc limit 5

上面的sql可以在hibernate中进行以下操作。

Criteria criteria = session.createCriteria(UserHistory.class); criteria.addOrder(Order.desc("pwdDate")); List<UserHistory> list = criteria.setMaxResults(5).list();

1 个答案:

答案 0 :(得分:1)

以下工作。关键是为Native SQL创建SQLQuery。

String SQL = 
"SELECT A.* FROM \n" +
"(select * \n" +
" from user_history$ order by pwdDate desc limit 5 ) AS A \n" + 
"where pwd = AES_ENCRYPT(:pwd, 'key_str') \n";

Query query = session.createSQLQuery(SQL);
query.setParameter("pwd", psw);
List<UserHistory> list = query.list();