gpt4 book ai didi

java - HQL:处理特殊字符

转载 作者:行者123 更新时间:2023-12-01 22:39:47 24 4
gpt4 key购买 nike

我尝试使用 HQL 从数据库中获取值,但由于值包含特殊字符而出现异常。我无法弄清楚为什么。

下面是我正在尝试的代码:

    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();

pojo 如下所示:酒店.java

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

HotelMapping.java

public class HotelMapping{

@OneToOne(cascade = CascadeType.ALL)
Hotel hoteID

String location;
}

查询字符串

Query query = session.createQuery("from HotelMapping hm where hm.hotelID.hotelName='"+hotelName+"'"); 给出以下异常:

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']

我尝试转义撇号,但没有成功。我什至尝试设置查询参数,但再次出现异常

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

它说线程“main”org.hibernate.QueryParameterException中的异常:无法找到命名参数[hotelName]

请问有人可以帮助我实现特殊字符处理的通用解决方案吗?

最佳答案

您永远不应该使用串联来传递这样的动态参数。这不仅效率低下,而且不健壮(因为参数值中的单引号会使查询无效)并且不安全,因为恶意用户可以传递一个改变查询语义的值(谷歌搜索“SQL注入(inject)攻击”) ”)。

相反,使用参数:

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

关于java - HQL:处理特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com