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)类似
不过它只能显示当前类有关的属性,不支持多态!

    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值