---
title: "hibernate 包含下划线的模糊查询"
author: "sinly"
date: "2013-04-09T08:33:26Z"
tags: []
categories: ["编程语言"]
slug: "hibernate"
draft: false
lastmod: "2013-04-09T08:33:26Z"
id: 1844226
url: "https://sinly.iteye.com/blog/1844226"
---

在模糊查询时，如果使用到了的条件包括"_"，在查询时，需要使用到转义字符对"_"进行转义，具体详细看下列代码：

```java


		name=name.replaceAll("\\_", "\\\\\\\\_");
			final String _name = name;
			List<Integer> cuIdList = super.getHibernateTemplate().execute(new HibernateCallback<List<Integer>>() {
				@SuppressWarnings("unchecked")
				@Override
				public List<Integer> doInHibernate(Session session) throws HibernateException, SQLException {
					StringBuffer sql = new StringBuffer(200);
					sql.append("select ")
					   .append("c.id")
					   .append(" from s c ")
					   .append("where c.control_unit_id in(:controlUnitId)")
					   .append(" and c.name like '%")
					   .append(_name)
					   .append("%' ESCAPE '\\\\'");
					SQLQuery query = session.createSQLQuery(sql.toString());
					query.setParameterList("controlUnitId", unitIdWithPrivilege);
					return query.list();
				}
			});

```