gpt4 book ai didi

hibernate - 如何使用 Hibernate/DB2 按 CLOB 列排序

转载 作者:行者123 更新时间:2023-12-03 06:55:25 24 4
gpt4 key购买 nike

我正在使用 Hibernate 4 和 DB2 10.1。当我按映射到 CLOB 列的属性对实体 (criteria.addOrder(...)) 进行排序时,出现以下错误:

[...] could not extract ResultSet:.org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:88)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2062)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1859)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:906)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:348)
at org.hibernate.loader.Loader.doList(Loader.java:2550)
at org.hibernate.loader.Loader.doList(Loader.java:2536)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2366)
at org.hibernate.loader.Loader.list(Loader.java:2361)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:124)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1587)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
[...]
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-134, SQLSTATE=42907, SQLERRMC=TEXT7_0_0_, DRIVER=4.15.100
[...]

原因是 DB2 无法按 CLOB 列排序。所以下面的语句将会失败:

SELECT * FROM MY_TABLE ORDER BY CLOB_COLUMN; 

一种可能的解决方案是将 CLOB 转换为 VARCHAR 进行排序。所以这工作正常:

SELECT * FROM MY_TABLE ORDER BY CAST(CLOB_COLUMN AS VARCHAR(1000));

如何让 Hibernate 进行这样的特殊处理?

最佳答案

我通过子类化org.hibernate.criterion.Order并覆盖toSqlString(...)解决了我的问题。我的实现称为 DB2Order 并将所有调用委托(delegate)给 super,除非它检测到 DB2Dialect 并且其中一个排序列的类型为 CLOB。

在我的代码中我曾经调用:

if (sortProperty.isAscending()) {
criteria.addOrder(Order.asc(sortPropertyPath));
} else {
criteria.addOrder(Order.desc(sortPropertyPath));
}

现在我打电话:

if (sortProperty.isAscending()) {
criteria.addOrder(new DB2Order(sortPropertyPath, true));
} else {
criteria.addOrder(new DB2Order(sortPropertyPath, false));
}

我的 DB2Order 实现的一些细节:

/**
* Specialized subclass of Hibernate's {@link Order} that performs special
* handling for DB2 databases. The general strategy is to let the superclass
* perform all processing except for special cases. Special cases covered are:
* <ul>
* <li>Sorting by {@code CLOB} columns. {@code CLOB} columns cannot be sorted
* directly by DB2, e.g. the SQL statement
* <p><code>SELECT * FROM MY_TABLE ORDER BY CLOB_COLUMN;</code>
* <p>will fail with
* <p><code>DB2 SQL Error: SQLCODE=-134, SQLSTATE=42907</code>
* <p>This class identifies sorting by CLOB columns and generates an SQL string
* that casts {@code CLOB} to a {@code VARCHAR} for sorting, rendering
* <p><code>SELECT * FROM MY_TABLE ORDER BY CAST(CLOB_COLUMN AS VARCHAR(1000));</code>
* <p>(which is successfully executed by DB2).
* <p><i>Note that this approach will trim {@code CLOB} entries that are larger
* than the {@code VARCHAR} casted to. So sorting may not be exact for long
* values.</i>
* </ul>
*/
public class DB2Order extends Order {
...
private static final int VARCHAR_SIZE = 1000;
private static final String CAST_PREFIX = "CAST(";
private static final String CAST_SUFFIX = " AS VARCHAR(" + VARCHAR_SIZE + "))";
...
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
if (isDB2(criteriaQuery) && isClob(criteria, criteriaQuery)) {
return toSqlStringWithClobTypeCast(criteria, criteriaQuery);
}
return super.toSqlString(criteria, criteriaQuery);
}

private String toSqlStringWithClobTypeCast(Criteria criteria, CriteriaQuery criteriaQuery) {
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria,
getPropertyName());
Type type = criteriaQuery.getTypeUsingProjection(criteria,
getPropertyName());
StringBuilder fragment = new StringBuilder();
for (int i = 0; i < columns.length; i++) {
final StringBuilder expression = new StringBuilder();
SessionFactoryImplementor factory = criteriaQuery.getFactory();
int sqlType = type.sqlTypes(factory)[i];
boolean lower = false;
if (isIgnoreCase()) {
lower = sqlType == Types.VARCHAR
|| sqlType == Types.CHAR
|| sqlType == Types.LONGVARCHAR;
}
boolean clob = (sqlType == Types.CLOB);
if (lower) {
expression.append(factory.getDialect().getLowercaseFunction())
.append('(');
}
if (clob) {
expression.append(CAST_PREFIX);
}
expression.append(columns[i]);
if (clob) {
expression.append(CAST_SUFFIX);
}
if (lower) {
expression.append(')');
}
fragment.append(factory.getDialect().renderOrderByElement(
expression.toString(), null, isAscending() ? "asc" : "desc",
NullPrecedence.NONE));
if (i < columns.length - 1) {
fragment.append(", ");
}
}
return fragment.toString();
}

private boolean isClob(Criteria criteria, CriteriaQuery criteriaQuery) {
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria,
getPropertyName());
Type type = criteriaQuery.getTypeUsingProjection(criteria,
getPropertyName());
for (int i = 0; i < columns.length; i++) {
SessionFactoryImplementor factory = criteriaQuery.getFactory();
int sqlType = type.sqlTypes(factory)[i];
if (sqlType == Types.CLOB) {
return true;
}
}
return false;
}

private boolean isDB2(CriteriaQuery criteriaQuery) {
return criteriaQuery.getFactory().getDialect() instanceof DB2Dialect;
}
}

关于hibernate - 如何使用 Hibernate/DB2 按 CLOB 列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29744868/

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