【问题标题】:Hibernate Regexp MySQL休眠正则表达式 MySQL
【发布时间】:2013-07-17 14:29:26
【问题描述】:

我问这个问题是为了展示 MySQL 和 Hibernate 如何使用正则表达式相互工作。

问题:

SELECT * FROM table WHERE regexp column '\d'

解决方案:

转到我的答案。

希望这会有所帮助。

【问题讨论】:

    标签: mysql regex hibernate


    【解决方案1】:

    基本上,要在 Hibernate 中使用 MySQL regexp 函数,我们需要创建一个“SQLFunctionTemplate”。

    现在,怎么做:

    首先:创建一个名为“AppMySQLDialect”的类并从 MySQLDialect 扩展,然后覆盖空构造函数,最后注册 regexp 函数:

    public class AppMySQLDialect extends MySQLDialect {
        public AppMySQLDialect() {
            super();
            /**
             * Function to evaluate regexp in MySQL
             */
            registerFunction("regexp", new SQLFunctionTemplate(Hibernate.INTEGER, "?1 REGEXP ?2"));
        }
    }
    

    好的,现在让我们如下使用它:

    FROM Entity E WHERE regexp(E.string2evaluate, '\d') = 1
    

    创建您的 HibernateQuery 并执行。

    【讨论】:

      【解决方案2】:
      String range = "ABCD";
      
      List<HRTrainee> hrTrainees =
            (List<HRTrainee>)sessionFactory.getCurrentSession().createCriteria(HRTrainee.class)
      
      .add(Restrictions.sqlRestriction("name REGEXP '^["+range+"]'")).list();
      
      return hrTrainees;
      

      【讨论】:

        【解决方案3】:

        REGEXP 在 MySQL 中被视为关键字。用户可以通过注册关键字在休眠过滤器中使用 REGEXP。 创建一个类 'CustomMySQL5InnoDBDialect' 扩展 MySQL5InnoDBDialect 并注册关键字如下:

        public class CustomMySQL5InnoDBDialect extends MySQL5InnoDBDialect {
        
        public CustomMySQL5InnoDBDialect() {
            super();
           /* register regexp keyword */
            registerKeyword("regexp");
        }
        }
        

        然后将persistence.xml中的hibernate-dialect属性改成

        <property name="hibernate.dialect" value="com.CustomMySQL5InnoDBDialect"/>
        

        用户可以在休眠过滤器中使用正则表达式,如下所示

        @Filters(value = {  @Filter(name="applyStudentFilter",condition="id in (select s.id from student s WHERE s.address REGEXP :addressValue)"),
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-26
          • 2020-08-05
          • 1970-01-01
          相关资源
          最近更新 更多