我正在尝试通过DAO类匹配一个hibernate实体,第一种方法有效但第二种'findByMatchingName()'失败,下面有例外。这个条款'%?%'>有什么问题? ?
public class RunnerDaoImpl extends GenericDaoImpl implements RunnerDao
{
protected Class<Runner> getEntityClass() {
return Runner.class;
}
// Works
public List<Runner> findByExactName(String name)
{
return super.getHibernateTemplate().find("from Runner r where concat(r.firstname,' ',r.surname) LIKE =",new String[]{name});
}
// Fails
public List<Runner> findByMatchingName(String name)
{
return super.getHibernateTemplate().find("from Runner r where concat(r.firstname,' ',r.surname) LIKE '%?%'",new String[]{name});
}
}
例外
java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:79)
at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:85)
at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:421)
at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:393)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:918)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912)
at ie.bhaa.dao.RunnerDaoImpl.findByName(RunnerDaoImpl.java:15)
at ie.bhaa.dao.RunnerDaoTest.findRunnerByName(RunnerDaoTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
答案 0 :(得分:3)
您需要将wildchar(%)
添加到参数而不是查询。请修改您的第二个查询,如下所示。
// This will work!
public List<Runner> findByMatchingName(String name)
{
return super.getHibernateTemplate().find(
"from Runner r where concat(r.firstname,' ',r.surname)
LIKE ?",new String[]{"%"+name+"%"});
}
答案 1 :(得分:1)
将%
放在查询参数中而不是查询本身中,因此参数将变为"%" + name + "%"
。