2011-12-02 78 views
1

我试图使用mysql find_in_set字符串函数在休眠,但遗憾的是我不能能够使用它,甚至用mysqldialect但没有人创造这些寄存器的功能调用MySQL的功能处于休眠

registerFunction("findInSet",newSQLFunctionTemplate(Hibernate.STRING,"FIND_IN_SET(?1,?2)")); 
registerFunction("findInSet",newSQLFunctionTemplate(Hibernate.INTEGER,"FIND_IN_SET(?1,?2)")); 
registerFunction("findInSet",new StandardSQLFunction("find_in_set", Hibernate.INTEGER)); 

试图返回VARCHAR正在工作......任何人都可以告诉我如何在hibernate中使用mysql字符串函数。或对上述寄存器功能的任何更改。

由于事先

最好的问候, 拉贾。

回答

0

通过像图所示

public class MySqlDialectExtended extends MySQLDialect { 

public MySqlDialectExtended() { 
    super(); 
    registerFunction("date_add_interval", new SQLFunctionTemplate(Hibernate.DATE, "date_add(?1, INTERVAL ?2 ?3)")); 
    registerFunction("date_sub_interval", new SQLFunctionTemplate(Hibernate.DATE, "DATE_SUB(?1, INTERVAL ?2 ?3)")); 
    registerFunction("weekofyear", new StandardSQLFunction("weekofyear", Hibernate.INTEGER)); 
    registerFunction("group_concat", new StandardSQLFunction("group_concat", Hibernate.STRING)); 
} 

}

延伸mysqldialect创建一个类,并在查询中使用它像这样

new Query(" >= date_sub_interval(CURRENT_DATE(),1, DAY)"); 
1

如果函数返回string or varchar值,调用函数很简单。

session.createSQLQuery("select my_super_fn(:param1)")

my_super_fn与参数参数1你的函数的名称。

要测试语法,请尝试使用此代码获取当前服务器日期。

Date d = (Date)session.createSQLQuery("select CURDATE()").uniqueResult(); 
System.out.println(d); 

对于其他类型的功能,请参考有关如何操作的问题here

+0

嗨,感谢您的答复..但你给的想法是不是在这种格式工作。查询查询= this.entityManager.createQuery(“选择FIND_IN_SET()”)..你可以给我一个想法如何使用与实体经理在休眠。 – user503285

+0

您使用的是JPA吗?你得到什么错误?与此同时,您应该使用** [createNativeQuery](http://docs.oracle.com/javaee/5/api/javax/persistence/EntityManager.html#createNativeQuery(java.lang.String))**。 – ManuPK

+0

我已经通过使用createnativequery解决了上述问题 – user503285

0

这个工作对我来说:

package mypackage; 

import org.hibernate.dialect.MySQL5InnoDBDialect; 
import org.hibernate.dialect.function.SQLFunctionTemplate; 
import org.hibernate.type.BooleanType; 

public class CustomSqlDialect extends MySQL5InnoDBDialect { 
    public CustomSqlDialect() { 
     registerFunction("find_in_set", new SQLFunctionTemplate(IntegerType.INSTANCE, "find_in_set(?1, ?2)"); 
    } 
} 

并设置th在你的JPA配置文件:

<property name="hibernate.dialect" value="mypackage.CustomSqlDialect"/> 

最后,find_in_set你应该确保查询条件为find_in_set(...) > 0。如果没有比较运算符,则使用find_in_set()将无法​​执行AST错误。

此外,你应该显然覆盖适当的方言和包名称。