2014-10-06 39 views
2

我从事的是hibernate。
下面的代码曾在MSSQL很好,但在MySQL允许误差用于在MySQL和SQL Server中连接字符串的SQL语句

代码:

Criteria criteria = session.createCriteria(table1.class); 
    criteria.add(Restrictions.sqlRestriction("(select this11_.um_email as y0_ from table2 this11_ where this11_.id='"+IDvalue+"') like '%'+this_.post_id+'%'")); 

堆栈跟踪:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+this_.post_id+'%'' at line 1 
org.hibernate.exception.SQLGrammarException: could not execute query 
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67) 
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) 
at org.hibernate.loader.Loader.doList(Loader.java:2223) 
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104) 
at org.hibernate.loader.Loader.list(Loader.java:2099) 
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:94) 
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1569) 
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:283) 

任何人可以帮我解决了这个?

回答

0

Mysql不允许使用带有文本的+;使用CONCAT()代替:

... like CONCAT('%', this_.post_id, '%') 

CONCAT()也能在MSSQL。

+0

ya它工作正常的MySQL,但它不会为mssql.My应用程序与mssql和mysql连接。 – 2014-10-06 14:00:37

+0

@sejal'CONCAT()'是SQL标准的一部分,也适用于mssql。该解决方案适用于mysql和mssql。 – Bohemian 2014-10-06 14:14:42

+0

当我尝试在mssql中执行此查询时,它会给出错误,如“消息195,级别15,状态10,行2 'CONCAT'不是一个公认的内置函数名称。” – 2014-10-06 14:16:24

0

也许这将帮助你

criteria.add(Restrictions.sqlRestriction("(select this11_.um_email as y0_ from table2 this11_ where this11_.id='"+IDvalue+"') LIKE CONCAT('%', {alias}.post_id ,'%')"); 
+0

没有它没有工作... – 2014-10-07 05:07:51

+0

任何新的错误? – 2014-10-07 05:19:32

+0

没有收到错误,但查询生成错误。它像'喜欢'%this_.post_id%'这给出了错误的输出.. – 2014-10-07 05:44:41

0

您可以根据数据库的方言创建查询。在您的Criteria中使用customQuery字符串。

String customQuery = ""; 
SessionFactory sessionFactory = session.getSessionFactory(); 
Dialect dialect = ((SessionFactoryImplementor) sessionFactory).getDialect(); 
String dialectString = dialect.toString(); 

if(dialectString.equals("org.hibernate.dialect.SQLServerDialect")){ 
    customQuery = "MSSQL_Query"; 
    ... 
}else if(dialectString.equals("org.hibernate.dialect.MySQLDialect") 
     || dialectString.equals("org.hibernate.dialect.MySQLInnoDBDialect") 
     || dialectString.equals("org.hibernate.dialect.MySQLMyISAMDialect")){ 
    customQuery = "MySQL_Query"; 
    ... 
}