2014-10-06 36 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"; 
    ... 
}