如何在hql搜索字符串中允许点字符?

时间:2018-02-28 15:19:02

标签: hibernate hql

@Entity
@Audited
public class Tag {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    // setters and getters
}

1:

    List<Tag> tags = sessionFactory.getCurrentSession()
                    .createQuery("from Tag as t where t.name=:name",Tag.class)
                    .setParameter("name", "Mr.John")
                    .getResultList();

             if(tags == null || tags.isEmpty())
              System.out.println("Did not find Result");
             else
              System.out.println("Found Result");

打印:

Did not find Result

2:

List<Tag> tags = sessionFactory.getCurrentSession()
                .createQuery("from Tag as t where t.name='Mr.John'",Tag.class)
                .getResultList();

         if(tags == null || tags.isEmpty())
          System.out.println("Did not find Result");
         else
          System.out.println("Found Result");

打印:

Found Result

注意不使用setParameter会产生正确的结果

在使用setParameter防止SQL注入时,如何在hql搜索字符串中允许使用点字符?

Ps:我正在使用Hibernate 5.2.6

2 个答案:

答案 0 :(得分:1)

但在我的代码中,它在两种情况下都能正常工作:

1)使用SetParameter():

 List<Book> list = entityManager.createQuery("from Book b where b.name=:nm").setParameter("nm", "Mr.Angad").getResultList();
if(list == null || list.isEmpty())
    System.out.println("Record not found :( ");
else
    System.out.println("Record found :) ");

o/p: Record found :)

2)没有SetParameter:

  List<Book> list = entityManager.createQuery("from Book b where b.name='Mr.Angad'").getResultList();
if(list == null || list.isEmpty())
    System.out.println("Record not found :( ");
else
    System.out.println("Record found :) ");

 o/p : Record found :)

答案 1 :(得分:0)

AFAIK。您已经受到sql注入的保护,因为您通过Session接口方法设置了这些参数。如果出现异常错误,您的查询将被评估为HQL,因此无法进行SQL注入。一个sql注入将这些参数连接(字符串连接)到本机(调用createSQLQuery方法)sql查询

使用setString btw。

相关问题