如何在Hibernate的HQL中转义保留字
我用下面的查询来获得java.util.Map
与指数id
,text
以及object
:
Query q = mySession.createQuery( "SELECT u.id AS id, u.name AS text, u AS object FROM User u")
.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
…但object
似乎是保留字。例如obj
可以。MySQL使用反引号转义的当前方式是如何在HQL中转义 别名 ?
使用反引号会出现以下错误:
Exception in thread "main" org.hibernate.QueryException: unexpected char: '`' [SELECT u.id AS id, u.name AS text, u AS `object` FROM User u]
回答:
您可以通过使用自定义“别名映射”转换器的解决方法来实现,因此您的代码将更改为如下所示
Query q = mySession.createQuery( "SELECT u.id AS id, u.name AS text, u AS obj FROM User u")
.setResultTransformer(
AliasToMapTransformer.renameAlias("obj", "object").build()
);
然后使用此类:
public class AliasToMapTransformer extends BasicTransformerAdapter { private Map<String, String> renameAliasMap;
public AliasToMapTransformer(Map<String, String> renameAliasMap) {
this.renameAliasMap = (renameAliasMap == null) ? Collections.<String, String>emptyMap() : renameAliasMap;
}
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
Map<String, Object> result = new HashMap<String, Object>(tuple.length);
for (int i = 0; i < tuple.length; i++) {
String alias = aliases[i];
if (alias != null) {
String newAlias = renameAliasMap.get(alias);
result.put((newAlias != null) ? newAlias : alias, tuple[i]);
}
}
return result;
}
public static Builder renameAlias(String alias, String newAlias) {
return new Builder().renameAlias(alias, newAlias);
}
public static class Builder {
private Map<String, String> aliasConversionMap = new HashMap<String, String>();
public Builder renameAlias(String alias, String newAlias) {
aliasConversionMap.put(alias, newAlias);
return this;
}
public AliasToMapTransformer build() {
return new AliasToMapTransformer(aliasConversionMap);
}
}
}
以上是 如何在Hibernate的HQL中转义保留字 的全部内容, 来源链接: utcz.com/qa/422939.html