JPA:如何使用SHA1加密保留列?

时间:2011-10-23 20:25:06

标签: java jpa jpql

我对JPA(以及扩展的JPQL)相当新。希望有人能用这个问题来启发我。

我正在尝试执行的查询...

String query = "select u from user u where u.email = '" + userEmail + "' and u.password = sha1('"+ userPassword + "')";
List resultList = emf.createEntityManager().createQuery(query).getResultList();

我正在接受以下例外......

Caused by: Exception [EclipseLink-8025] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing the query [select u from Utilisateur u where u.email = 'myuser' and u.mot_Passe = sha1('mypassword')], line 1, column 73: unexpected token [(].
Internal Exception: NoViableAltException(83@[()* loopback of 383:9: (d= DOT right= attribute )*])
    at org.eclipse.persistence.exceptions.JPQLException.unexpectedToken(JPQLException.java:372)
...

显然,我在这里遗失了一些东西,我是否应该以某种方式逃避这个角色?用另一种方式指定它?我非常感谢你们的任何帮助。

3 个答案:

答案 0 :(得分:3)

我认为JPA没有sha1功能。所以你有两个选择:

  1. 您可以在Java代码上实现sha1函数,并在加载查询中的参数之前使用它们。

    String query = "select u from user u where u.email = :userEmail" +
       " and u.password = :userPassword";
    Query jpqlQuery = em.createQuery(query)
        .setParameter("userEmail", userEmail)
        .setParameter("userPassword",sha1(userPassword));
    
  2. 如果您的数据库具有sha1函数,则可以编写本机查询。请检查此链接:http://www.oracle.com/technetwork/articles/vasiliev-jpql-087123.html

    List<Customer> customers = (List<Customer>)em.createNativeQuery
            ("SELECT * FROM customers", jpqlexample.entities.Customer.class)
                          .getResultList(); 
    Iterator i = customers.iterator();
    Customer cust;
    while (i.hasNext()) {
        cust = (Customer) i.next();
        //do something
    }
    

答案 1 :(得分:1)

通过Query接口设置参数,而不是将它们字面添加到JPQL String。这样你就可以保护自己免受SQL injection

的侵害
String query =
   "select u from user u where u.email = :userEmail"
   + " and u.password = sha1(:userPassword)";
Query jpqlQuery = em.createQuery(query)
    .setParameter("userEmail", userEmail)
    .setParameter("userPassword",userPassword)

答案 2 :(得分:0)

在EclipseLink中,您可以使用FUNC查询字来使用特定于数据库的函数。

“从用户u中选择你,其中u.email =:email和u.password = FUNC('sha1',:password)”

请参阅, http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Support_for_Native_Database_Functions