2

我有以下在 mysql 中完美运行的查询。

SELECT * FROM Orders as o, Products as p  where o.productinfo RLIKE p.code;

在这里,我将两个表 Orders 和 Products 与 RLIKE 连接起来。

我正在尝试在 Hibernate 中实现相同的功能。

Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo RLIKE p.code");
List<Object[]> results = query.getResultList();

当我使用 RLIKE 时,在运行时会抛出以下错误。

{"errormessage":"org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: RLIKE 

我尝试使用 LIKE 查询来实现相同的功能,并将其与 '%p.code%' 匹配。

Query query = session.createQuery("FROM Orders as o, Products as p  where o.productinfo LIKE '%p.code%'");

但它与字符串“p.code”而不是值匹配。

HQL 中的 RLIKE 等价物是什么?在 HQL 中是否有不同的方法可以使用 LIKE 连接两个表?

谢谢。

@YCF_L 回答:对于任何试图在 Hibernate(mysql)中使用 like 运算符连接两个表的人都可以通过以下方式进行操作。

SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');
4

2 回答 2

1

Hibernate Query 中 mysql RLIKE 运算符的等效项是什么?

RLIKE是同义词,REGEXP因此您可以在 hibernate using 中实现它REGEXP_LIKE,您可以在此处查看:How to search in multiple columns using one like operator in HQL (hibernate sql)


我尝试使用 LIKE 查询来实现相同的功能,并将其与 '%p.code%' 匹配。

..., Products as p  where o.productinfo LIKE '%p.code%'");

但它与字符串“p.code”而不是值匹配。

这是真的,因为您没有传递正确的值p.code,而是像字符串一样传递它,而是有两种方法:

Query query = session.createQuery("....Products as p  where o.productinfo LIKE '%:code%'");
//------------------------------------------------------------------------------^^^^^^^
query.setParameter("code", p.code);

或者您可以将您的代码与您的查询连接起来,但第一个解决方案更好。

Query query = session.createQuery("....  where o.productinfo LIKE '%" + p.code + "%'");

编辑

您可以在不指定 like 的情况下将 like 与 CONCAT 一起使用''

SELECT * FROM Orders as o, Products as p  where o.productinfo LIKE CONCAT('%',p.code,'%');
于 2017-03-29T11:09:34.323 回答
0

您可以通过以下方式检查正则表达式: Restrictions.sqlRestriction(word REGEXP '^[AZ][A-Za-z]*$')

请检查对这种情况有帮助的链接:带有条件的正则表达式

于 2017-03-29T11:17:54.677 回答