关于Hibernate的对象标识符increment

    技术2026-09-04  20

    以前,使用Orlace数据库的,为了让其主键id自动增长,是这样设置的:

    <id name="id" type="java.lang.Integer"> <column name="ID" precision="22" scale="0" /> <generator class="sequence"> <param name="sequence">seq_test</param> </generator> </id>

    这样做的话,可以实现主键id主动的自动增长,但是需要创建一个序列 (seq_test).

    今天,发现这么做太麻烦了——主键id交给Hibernate生成不就完了。

    其设置如下:

    <id name="id" type="java.lang.Integer"> <column name="ID" precision="22" scale="0" /> <generator class="increment" /> </id>

    其中increment 是由Hibenate自动生成的,每次加1,而且,还不用在数据库中创建序列。

    有的时候,就算创建了序列,可能因为操作发生了异常,而产生如下情况:

    即,id顺序号断开了(尽管,id只是一个代理主键,没有什么特定业务含义,但是还是希望它不要"断号")。

    而使用increment 来生成主键id就不会发生这样的情况(前提,请最好设置事务 )。

    例如:

    package cdl; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Demo { public static void main(String[] args) { Configuration cfg=new Configuration().configure(); SessionFactory sf=cfg.buildSessionFactory(); Session session=sf.openSession(); Transaction tx=session.beginTransaction(); Test test=new Test(); test.setName("rootrootrootrootrootrootrootrootrootrootrootrootrootrootroot"); //这个是非法的 //test.setName("root"); // 这个是合法的 session.save(test); tx.commit(); session.close(); } }

    这个对象是不会插入到数据库的(name的长度是20位),而合法长度的就可以。

    而且,主键是由Hibernate负责生成的,也不会出现“断号”的情况

    总结:

    除了Oracle,MySQL,MS Server都可以使用这种主键策略。

     

    最新回复(0)