您的位置:首页 > 其它

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

2015-07-25 22:15 357 查看
原本以为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)类似
不过它只能显示当前类有关的属性,不支持多态!

    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: