如何在Hibernate的HQL中转义保留字

如何在Hibernate的HQL中转义保留字,第1张

如何在Hibernate的HQL中转义保留字

您可以通过使用自定义“别名映射”转换器的解决方法来实现,因此您的代码将更改为如下所示

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5047876.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存