自定義 insert、update、delete


Hibernate 3的映射文件中新增了<sql-insert>、<sql-update>與< sql-delete>三個標籤,您 可以在這三個標籤中使用SQL自定義您的INSERT、UPDATE、DELETE,也就是儲存、更新、刪除資料時的行為,例如:
  • User.hbm.xml
<?xml version="1.0" encoding="utf-8"?> 
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="onlyfun.caterpillar.User" table="user">

<id name="id" column="id">
<generator class="native"/>
</id>

<property name="name" column="name"/>
<property name="age" column="age"/>

<sql-insert>
INSERT INTO user (name, age) VALUES (?, ?)
</sql-insert>
<sql-update>
UPDATE user SET name=?, age=?, WHERE id=?
</sql-update>
<sql-delete>
DELETE FROM user WHERE id=?
</sql-delete>

</class>

</hibernate-mapping>

? 對應的順序是映射文件中屬性出現的順序,假設您儲存物件:
session = sessionFactory.openSession();
tx = session.beginTransaction();
           
session.save(user);
tx.commit();
session.close();

則執行結果中顯示的SQL語句會是您自定義的語句,而不是由 Hibernate自動生成的語句:
Hibernate:
        INSERT INTO user (name, age) VALUES (?, ?)