package com.framework.util;
import java.sql.Types;
import org.hibernate.Hibernate;
import org.hibernate.dialect.function.SQLFunctionTemplate;
public class MySQL5Dialect extends org.hibernate.dialect.MySQL5Dialect {
public MySQL5Dialect() {
super();
// register additional hibernate types for default use in scalar
// sqlquery type auto detection
//registerHibernateType(Types.LONGVARCHAR, Hibernate.TEXT.getName());//对应表中的列有 text类型的,数据库方言类型不一致导致问题
registerFunction("regexp", new SQLFunctionTemplate(Hibernate.STRING, "?1 REGEXP ?2"));//?1代表第一个参数,?2代表第二个参数
}
}
修改jdbc.properties
jdbc.hibernate.dialect=com.framework.util.MySQL5Dialect
调用
StringBuffer sb = new StringBuffer();
sb.append("from UserBean ub where 1=1 ");
if (up.getUserId() > 0) {
sb.append(" and ub.userId=" + up.getUserId());
}
if (up.getSex() != 0) {
sb.append(" and ub.sex=" + up.getSex());
}
if (up.getUserName() != null) {
sb.append(" and upper(ub.userName) like upper('%" + up.getUserName()
+ "%')");
}
if (up.getPetname() != null) {
sb.append(" and upper(ub.petname) like upper('%" + up.getPetname()
+ "%')");
}
if(up.getIsMail()>0){
sb.append(" and regexp(ub.userName,'^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$')=1 ");
// regexp(ub.userName,'^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$')=1
}
我想在hibernate sql语句中使用正则表达式,结果hibernate报错,通过在网上查找资料,发现可以使用hibernate的自定义函数可以解决这个问题!