简体   繁体   中英

a hibernate createQuery() prep statement

i've made this method for my Generic DAO

public T find(String column, String input) {
    Query query = em.createQuery("select e from " + type.getSimpleName()+ " e where e."+
    ":column = :input").setParameter("input", input).setParameter("column", column);
    return (T)query.getSingleResult();
}

It is supposed to be a generic find() method that allows every DAO that extends the abstract genericDAO class to use this method with different parameters.

So for example, the UserDAO would use this method with the arguments column = "userName" and input = userName.getText() < this is a textfield.

A RecordDAO could use it with column = recordName and input = "beatles"

I have a few questions about this method.

  1. will it work as it is now? Can i have 2 setParameter() methods and parameters in my creatQuery?

  2. Is using setParameter in this code helping the code become more safer? Is someone still able to do an SQL injection attack when it inputs SQL code instead of a username in the Textfield box of the program?

  3. Is there a more efficient way to make a versatile find() method like this one?

  4. what is being returned by getSingleResult() when nothing is found? NULL?

1.) Yes, you can.

2.) Yes. No.

3.) Depends on what your exact use case is.

4.) You can check out the javadoc of Query#getSingleResult . Hint:

NoResultException - if there is no result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM