2013-07-17 27 views
4

我問這個問題,以顯示MySQL和Hibernate如何與正則表達式相互工作。休眠正則表達式MySQL

問題:

SELECT * FROM table WHERE regexp column '\d' 

解決方案:

轉到我的答案。

希望這會有所幫助。

回答

3

基本上,要在Hibernate中使用MySQL regexp函數,我們需要創建一個「SQLFunctionTemplate」。現在

,如何做到這一點:

第一:創建一個名爲「AppMySQLDialect」,並從MySQLDialect擴展類,然後重寫空的構造函數,最後註冊的正則表達式功能:

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並執行。

3
String range = "ABCD"; 

List<HRTrainee> hrTrainees = 
     (List<HRTrainee>)sessionFactory.getCurrentSession().createCriteria(HRTrainee.class) 

.add(Restrictions.sqlRestriction("name REGEXP '^["+range+"]'")).list(); 

return hrTrainees;