如何在查询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:我决定编写解决方案,因为它是两个答案的组合。
最佳答案
最简单的方法是使用 Expressions.stringTemplate
Expressions.stringTemplate("SUBSTRING_INDEX({0},',',3)", columnPath)
更新
好的,我已经设法让它工作了。
我正在使用 H2 数据库
,所以我使用了函数 SUBSTR
。
QAcheteur ach = new QAcheteur("ach");
new JPASQLQuery(entityManager, new H2Templates())
.from(ach)
.list(Expressions.stringTemplate("SUBSTR({0}, 1, 3)", ach.ancestors));
关键是不使用 JPAQuery
,而是使用 JPASQLQuery
,因为此查询使用 native 函数。您所要做的就是关注this教程。
关于java - 返回从第 N 次出现开始的子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946582/