1. 程式人生 > >Hql 也可以進行DML操作update delete insert

Hql 也可以進行DML操作update delete insert

原本以為HQL(Hibernate Query  Language) 只是一種查詢語言,只能進行DDL操作,可是當我利用Hibernate的API進行update的時候,如果進行配置,預設就會更新整行!太不人道了!

  配置方法 :

在Annotation中 在屬性GET方法上加上@Column(updatable=false)

view plaincopy to clipboardprint? 
@Column(updatable=false)  
public int getAge() {  
return age;  
} 
@Column(updatable=false) 
public int getAge() { 
return age; 
}
第2種方法··使用XML中的 dynamic-update="true"

view plaincopy to clipboardprint? 
<class name="com.sccin.entity.Student" table="student" dynamic-update="true"> 
<class name="com.sccin.entity.Student" table="student" dynamic-update="true">
第三種就是HQL方法了!

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
        .setString( "newName", newName )
        .setString( "oldName", oldName )
        .executeUpdate();
tx.commit();
session.close();

 // insert只支援注意 ,只支援 INSERT INTO ... SELECT ... 形式,不支援 INSERT INTO ... VALUES ... 形式。

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlInsert = "insert into DelinquentAccount (id, name) select c.id, c.name from Customer c where ...";
int createdEntities = s.createQuery( hqlInsert )
        .executeUpdate();
tx.commit();
session.close();

INSERT 語句的偽碼是:INSERT INTO EntityName properties_list select_statement。
properties_list 和 SQL INSERT 語句中的欄位定義(column speficiation)類似
不過它只能顯示當前類有關的屬性,不支援多型!