接上回繼續,TMP_EMP中的ID是根據序列SQ_TMP_EMP來產生的,需要在TmpEmp.hbm.xml中設定:
<id name="id" type="long">
<column name="ID" not-null="true" sql-type="NUMBER" unique="true"/>
<generator class="sequence">
<param name="sequence">SQ_TMP_EMP</param>
</generator>
</id>
這樣運行時,Hibernate就會自動從SQ_TMP_EMP中取nextval用來填充到ID欄位中
範例程式碼:
先建立一個工具類
package app;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class HibernateUtils {private HibernateUtils(){}static SessionFactory sessionFactory;/* * 取得Hibernate的Session */public static Session getSession(){if (sessionFactory == null) {sessionFactory = new Configuration().configure().buildSessionFactory();}return sessionFactory.openSession();}/* * insert記錄 */public static boolean addObject(Object obj){Session ss = null;Transaction ts = null;boolean result = false;try{ss = getSession();ts = ss.beginTransaction();ss.save(obj);ts.commit();result = true;}finally{ss.close();}return result;}}
添加記錄的類
package app;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import domain.TmpEmp;import java.math.BigDecimal;import java.util.Calendar;import java.util.Date;import java.util.List;public class Hello {/** * @param args */public static void main(String[] args) {TmpEmp emp = new TmpEmp();emp.setName("張三峰");emp.setSalary(new BigDecimal(1000));emp.setSex('M');emp.setBirthday(new Date(1985-1900,12-1,1));//1985-12-1號boolean b = HibernateUtils.addObject(emp);if (b){System.out.println("插入成功,新記錄的ID是:" + emp.getId());}else{System.out.println("插入失敗!");}}}
運行結果:
Hibernate: select IGSA.SQ_TMP_EMP.nextval from dual
Hibernate: insert into IGSA.TMP_EMP (NAME, BIRTHDAY, SEX, SALARY, ID) values (?, ?, ?, ?, ?)
插入成功,新記錄的ID是:210