【发布时间】:2016-10-23 03:06:16
【问题描述】:
如何在查询JPA中QueryDsl中使用该功能
SUBSTRING_INDEX(str,delim,count)
返回字符串 str 在出现 count 分隔符 delim 之前的子字符串。
更新 1: 在尝试了这样的@MaciejDobrowolski 解决方案后:
QAcheteur ach = new QAcheteur("ach");
new JPAQuery(entityManager).from(ach)
.list( Expressions.stringTemplate("SUBSTRING_INDEX({0},',',1)", ach.ancestors) );
我收到了这个错误:
java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: '('
+-[METHOD_NAME] IdentNode: 'SUBSTRING_INDEX' {originalText=SUBSTRING_INDEX}
\-[EXPR_LIST] SqlNode: 'exprList'
+-[DOT] DotNode: 'acheteur1_.ancestors' {propertyName=ancestors,dereferenceType=PRIMITIVE,getPropertyPath=ancestors,path=ach.ancestors,tableAlias=acheteur1_,className=persistence.Acheteur,classAlias=ach}
| +-[ALIAS_REF] IdentNode: 'acheteur1_.ID_ACHETEUR' {alias=ach, className=persistence.Acheteur, tableAlias=acheteur1_}
| \-[IDENT] IdentNode: 'ancestors' {originalText=ancestors}
+-[QUOTED_STRING] LiteralNode: '',''
\-[NUM_INT] LiteralNode: '3'
更新 2:(解决方案)
按照@DraganBozanovic 的回答,我创建了我的自定义方言来使用No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode,因为SUBSTRING_INDEX 在JPA 中是未知的,所以我们使用我们自己的方言来使其工作。
package dialect;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StandardBasicTypes;
public class CustomMySQLDialect extends MySQL5Dialect {
public CustomMySQLDialect() {
super();
registerFunction("substring_index", new StandardSQLFunction("substring_index", StandardBasicTypes.STRING));
registerFunction("replace", new StandardSQLFunction("replace", StandardBasicTypes.STRING));
....
}
}
在 JPA 配置中
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...
...
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">dialect.CustomMySQLDialect</prop>
</props>
</property>
</bean>
P.S :我决定编写解决方案,因为它是两个答案的组合。
【问题讨论】:
-
你已经尝试了什么?
-
@Shachaf.Gortler 我尝试
path.substring(path.locate(",", count)),但定位函数不是从 N 次出现而是从索引开始 -
@Youssef 请尽可能分享您的代码。
-
okey @SkyWalker 我在执行测试查询时分享这部分内容,如果您想要其他内容,请告诉我。
标签: java hibernate jpa querydsl