简体   繁体   English

HQL:处理特殊字符

[英]HQL: Handling special characters

I am trying to fetch value from database using HQL but am getting exceptions because value contains special characters. 我正在尝试使用HQL从数据库中获取值,但由于值包含特殊字符而出现异常。 I am not able to figure out why. 我不知道为什么。

Below is the code i am trying: 下面是我正在尝试的代码:

    HotelMapping hotelMapping = null;
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction tx = session.getTransaction();
    tx.begin();
    String hotelName = "A Fisher's Inn Motel";
    Query query = session.createQuery("from HotelMapping hm where hm.hotelID.hotelName='"+hotelName+"'");
    HotelMapping mapping = query.uniqueResult();
    }
    tx.rollback();

    sessionFactory.close();

The pojos look like below: Hotel.java pojos如下所示: Hotel.java

public class Hotel{
    String hotelName;
    double price;
    //getters and setters
}

HotelMapping.java HotelMapping.java

public class HotelMapping{

     @OneToOne(cascade = CascadeType.ALL)
     Hotel hoteID

     String location;
}

The query string 查询字符串

Query query = session.createQuery("from HotelMapping hm where hm.hotelID.hotelName='"+hotelName+"'"); gives me below exception : 给我下面的异常:

Exception in thread "main" org.hibernate.QueryException: expecting ''', found '<EOF>' [from com.pb.model.HotelMapping hm where hm.hotelID.hotelName='A Fisher's Inn Motel']

I tried escaping the apostrophe but with no luck. 我尝试转义撇号,但没有运气。 I ven tried setting the query parameter but again i got exception 我尝试设置查询参数,但再次出现异常

query.setParameter("hotelName", "A Fisher's Inn Motel");

It says Exception in thread "main" org.hibernate.QueryParameterException: could not locate named parameter [hotelName] 它说Exception in thread "main" org.hibernate.QueryParameterException: could not locate named parameter [hotelName]

Please if someone could help me achieving a generalized solution for the special character handling? 请问有人可以帮助我实现特殊字符处理的通用解决方案吗?

You should never use concatenation to pass dynamic parameters like this. 您绝不应该使用串联来传递动态参数。 This is not only not efficient, but also not robust (since a single quote in the parameter value makes the query invalid) and insecure, since a malicious user could pass a value that changes the semantics of the query (google for "SQL injection attack"). 这不仅效率不高,而且不够健壮(因为参数值中的单引号会使查询无效)并且不安全,因为恶意用户可能会传递一个更改查询语义的值(针对“ SQL注入攻击的Google” ”)。

Instead, use parameters: 而是使用参数:

Query query = session.createQuery(
    "from HotelMapping hm where hm.hotelID.hotelName = :hotelName");
query.setString("hotelName", hotelName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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