Hibernate having difficulty with '@' character in HQL

痞子三分冷 提交于 2019-12-04 04:41:18

问题


Working with hibernate and spring social,

I am trying to query the database by email address. when i do this query:

public Account findAccountByUsername(String username) {

    Session session = sessionFactory.getCurrentSession();
    String selectQuery = "FROM Account as account WHERE account.username = "+username;
    Query query = session.createQuery(selectQuery);
    @SuppressWarnings("unchecked")
    List<Account> results = query.list();

  if (!results.iterator().hasNext())
        return null;        
    return results.iterator().next();       }

i get this exception

2013-01-22 14:37:13,090 [DEBUG] [HibernateTransactionManager,doBegin(),569] - Exposing Hibernate transaction as JDBC transaction [com.mchange.v2.c3p0.impl.NewProxyConnection@3b249bb2] 2013-01-22 14:37:13,352 [DEBUG] [QueryTranslatorImpl,parse(),272] - parse() - HQL: FROM masterPackage.model.orm.Account as account WHERE account.username = myEmail@gmail.com 2013-01-22 14:37:13,383 [DEBUG] [AbstractPlatformTransactionManager,processRollback(),843] - Initiating transaction rollback 2013-01-22 14:37:13,384 [DEBUG] [HibernateTransactionManager,doRollback(),672] - Rolling back Hibernate transaction on Session [org.hibernate.impl.SessionImpl@294a7134] 2013-01-22 14:37:13,385 [DEBUG] [JDBCTransaction,rollback(),186] - rollback

.......

2013-01-22 14:37:18,818 [WARN] [ProviderSignInController,oauth2Callback(),177] - Exception while handling OAuth2 callback (unexpected char: '@' [FROM masterpackage.model.orm.Account as account WHERE account.username = myEmail@gmail.com]). Redirecting to /signin

is there a way to work around this problem?

There is always a way to save the @ character in the email address as some other character, but i am asking if there is something better then this solution.


回答1:


Do not concatenate HQL query. Use named parameters instead. It is an implementation of Query Object Pattern in Hibernate.

For your case:

Session session = sessionFactory.getCurrentSession();
String selectQuery = "FROM Account as account WHERE account.username = :usernameParam";
Query query = session.createQuery(selectQuery);
query.setParameter("usernameParam", username);
@SuppressWarnings("unchecked")
List<Account> results = query.list();

if(results.isEmpty()){
    return null;
} else {
    return result;
}

Offtop: recommended never return null value for such method. Better is to return an empty collection. For example return new ArrayList<>(); Thus you able to use Null Object pattern implicitly.



来源:https://stackoverflow.com/questions/14458986/hibernate-having-difficulty-with-character-in-hql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!