如何在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

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

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 :)

afaik。您已经受到了SQL注入的保护,因为您正在通过会话接口方法设置这些参数。如果出现错误的例外,则您的查询将被评估为HQL,因此无法发生SQL注入。SQL注入将是串联(字符串串联(这些参数与本机(呼叫createsQlquery方法(SQL QUERY

使用setstring btw。

最新更新