接上回继续,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
当然,除用.hbm.xml来配置外,等效的注解方式,可以参考下面的写法:
1 @Id 2 @SequenceGenerator(name="bkdex_seq_generator",sequenceName="SQ_BKD_EX") 3 @GeneratedValue(generator="bkdex_seq_generator",strategy=GenerationType.SEQUENCE) 4 @Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0) 5 public BigDecimal getId() { 6 return this.id; 7 }
基本上这样就行了,但是实际运行会发现sequence每次并不是加1,而是一个其它的数,如果想要每次加1,参考下面这样:
1 @Id 2 @SequenceGenerator(name = "SEQ_ORDER", sequenceName = "SEQ_ORDER", allocationSize = 1) 3 @GeneratedValue(generator = "SEQ_ORDER", strategy = GenerationType.SEQUENCE) 4 @Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0) 5 public BigDecimal getId() { 6 return this.id; 7 }
allocationSize=1 这个是关键