【问题标题】:What's the equivalent of mysql RLIKE operator in Hibernate Query?Hibernate Query 中 mysql RLIKE 运算符的等效项是什么?
【发布时间】:2017-03-29 11:01:35
【问题描述】:

我有以下在 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,'%');

【问题讨论】:

    标签: java mysql hibernate hql rlike


    【解决方案1】:

    Hibernate Query 中的 mysql RLIKE 运算符等价于什么?

    RLIKEREGEXP 的同义词,因此您可以使用REGEXP_LIKE 在hibernate 中实现它,您可以在这里查看: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 与CONCAT 一起使用:

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

    【讨论】:

    • 感谢您的建议。我仍然无法解决问题。有没有办法用 like 加入两个表?这里的“p.code”是要连接的表中的列,而不是静态值。
    【解决方案2】:

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

    请查看对本案例有帮助的链接:Regular expression with criteria

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-15
      • 2014-08-21
      • 2011-10-09
      • 2011-12-12
      • 2012-01-24
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      相关资源
      最近更新 更多