java學習:Hibernate學習-oracle環境中配置實體類ID從序列產生

來源:互聯網
上載者:User

上回繼續,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  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.