2013-01-24 156 views
0

如何從Hibernate中刪除對象?休眠刪除

Session session = HibernateSession.getSessionFactory().openSession(); 
     org.hibernate.Transaction tx = session.beginTransaction(); 
     int q = session.createQuery("from Modele where (model='"+u.getModel() +"' and markaid='"+u.getMarki().getId()+"'").executeUpdate(); 
     // session.delete(u); 

     session.getTransaction().commit(); 

信息:不支持!使用AST翻譯...

當使用session.delete(u)相反,我得到這個

信息:在刪除處理處理瞬態實體

CREATE TABLE modele 
(
    id serial NOT NULL, 
    markaid integer NOT NULL, 
    cena numeric(100,2), 
    model character varying(32), 
    CONSTRAINT k_glwny PRIMARY KEY (id), 
    CONSTRAINT obcy FOREIGN KEY (markaid) 
     REFERENCES marki (id) MATCH SIMPLE 
     ON UPDATE NO ACTION ON DELETE CASCADE 
) 

<hibernate-mapping> 
    <class name="bazaMap.Modele" table="modele" schema="public"> 
     <id name="id" type="int"> 
      <column name="id" /> 
      <generator class="identity" /> 
     </id> 
     <many-to-one name="marki" class="bazaMap.Marki" fetch="select"> 
      <column name="markaid" not-null="true" /> 
     </many-to-one> 
     <property name="cena" type="java.lang.Double"> 
      <column name="cena" scale="0" /> 
     </property> 
     <property name="model" type="string"> 
      <column name="model" length="32" /> 
     </property> 
     <set name="wypozyczenias" inverse="true"> 
      <key> 
       <column name="modelid" not-null="true" /> 
      </key> 
      <one-to-many class="bazaMap.Wypozyczenia" /> 
     </set> 
    </class> 
</hibernate-mapping> 

這does not工作太

session.createQuery("from Modele where model = :mmodel and markaid = :mmarkaid").setParameter("mmodel", u.getModel()).setParameter("mmarkaid", u.getMarki().getId()).executeUpdate(); 
+1

不連接查詢。最好使用Query對象模板。 http://stackoverflow.com/questions/14458986/hibernate-having-difficulty-with-character-in-hql/14459137#14459137 – Taky

+0

@Taky:最好使用查詢參數或條件來構建動態查詢。 (查詢對象模式不解決查詢的創建)。 –

+0

@StefanSteinegger:我以爲查詢對象模式(http://martinfowler.com/eaaCatalog/queryObject.html)定義模式包含標準和查詢參數,不是嗎? – Taky

回答

0

我相信你的HQL缺少導致AST錯誤的DELETE關鍵字(基本上是一個HQL語法錯誤)。它應該是:

DELETE from Modele where (model='"+u.getModel() +"' and markaid='"+u.getMarki().getId()+"'" 

如果您想要使用delete方法(在hibernate 3中實際不贊成使用HQL),您必須確保將實體加載到刪除之前刪除它的同一個會話中它。

我一般使用HQL風格刪除,雖然我會建議使用命名參數,而不是字符串連接。