2017-07-28 30 views
0

我試圖運行在一個Hibernate會話的本地SQL刪除,但我得到一個異常抱怨表的別名。如果我在SQL客戶端中運行sql查詢,那麼它工作正常。休眠本地SQL表中找不到錯誤

String sql = 'delete c from child c join parent p on c.parent_id=p.id where p.some_id = :someId' 
SQLQuery deleteQuery = sessionFactory.currentSession.createSQLQuery(sql) 
deleteQuery.setParameter('someId', some.id.longValue()) 
deleteQuery.executeUpdate() 

異常在我的單元測試拋出:

[main] ERROR util.JDBCExceptionReporter - Table "C" not found; SQL statement: 

delete c from child c join parent p on c.parent_id=p.id where p.some_id = ? [42102-164] 

org.hibernate.exception.SQLGrammarException: could not execute native bulk manipulation query 
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92) 
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) 
at org.hibernate.engine.query.NativeSQLQueryPlan.performExecuteUpdate(NativeSQLQueryPlan.java:219) 
at org.hibernate.impl.SessionImpl.executeNativeUpdate(SessionImpl.java:1310) 
at org.hibernate.impl.SQLQueryImpl.executeUpdate(SQLQueryImpl.java:396) 
at org.hibernate.Query$executeUpdate.call(Unknown Source) 
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45) 
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108) 
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112) 

爲什麼這不起作用通過Hibernate有什麼建議?

回答

0

(編者)

使用表更好的名字。

String sql = 'DELETE child FROM child INNER JOIN parent ON child.parent_id = parent.id WHERE parent.some_id = :someId'; 

地址

這是適合你的示例代碼(我的):

... 

public boolean eliminar(Child some_id) 
{ 
    boolean result = false; 
    Session session = null; 
    Transaction rs = null; 

    try 
    { 
     session = sessionFactory.openSession(); 
     rs = session.beginTransaction(); 
     rs.setTimeout(5); 

     String query_string = "DELETE child FROM child INNER JOIN parent ON child.parent_id = parent.id WHERE parent.some_id = :someId"; 
     query_string.setParameter('someId', some_id); 
     Query q = session.createQuery(query_string); 
     q.executeUpdate(); 

     rs.commit(); 

     result = true; 
    } 
    catch(RuntimeException e) 
    { 
     try 
     { 
      rs.rollback(); 
     } 
     catch(RuntimeException rbe) 
     { 
      System.out.println(rbe.getMessage()); 
     } 
     System.out.println(e.getMessage()); 
    } 
    finally 
    { 
     session.close(); 
    } 
    return result; 
} 
... 
+0

與錯誤:錯誤util.JDBCExceptionReporter - 從孩子的SQL語句的語法錯誤「刪除爲C JOIN [*]父p於c.parent_id = p.id其中p.some_id =「?; SQL語句: 從Child C級刪除c.parent_id = p.id其中p.some_id加入母公司P =? [42000-164] – shuttsy

+0

編輯我進入,用新的查詢再試一次。我替換表的名稱的別名。錯誤是mysql不匹配表。 – MikeSouto

+0

仍然在「從」部分 – shuttsy