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