Hibernate主键生成策略之MultipleHiLoPerTableGenerator
昨天遇到一个问题:有两个相关联的PO类,一个是用Annotation注释的,一个是用hbm.xml文件映射的。现在主键生成策略是用一张表维护所有的表的主键的。
JPA的Annotation注解如下:
@Id @GeneratedValue(strategy = GenerationType.TABLE,generator="customer_gen") @TableGenerator(name = "customer_gen", table="tb_generator", pkColumnName="gen_name", valueColumnName="gen_value", pkColumnValue="CUSTOMER_PK", allocationSize=1 )
在这里不多说,因为本人不习惯用Annotation,具体请参考如下两个地址:http://zpfadmin.iteye.com/blog/670319,http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-declaration-id-enhanced-optimizers
正因为不习惯用Annotation,所以非坚持用xml配置文件,但用如native,identity等对数据库移植有不是很全面。
后面发现了hibernate的这个主键生成类:org.hibernate.id.MultipleHiLoPerTableGenerator
这个类跟上面的JPAAnnotation同等功能,配置如下:
<generator class="org.hibernate.id.MultipleHiLoPerTableGenerator" > <param name="table">UINRepository</param> <param name="primary_key_column">category</param> <param name="value_column">counter</param> <param name="primary_key_value">intimateList</param> <param name="primary_key_length">100</param> <param name="max_lo">0</param> </generator>
参数说明:
table:tablename(default<tt>hibernate_sequences</tt>)
primary_key_column:keycolumnname(default<tt>sequence_name</tt>)
value_column:hivaluecolumnname(default<tt>sequence_next_hi_value</tt>)
primary_key_value:keyvalueforthecurrententity(defaulttotheentity'sprimarytablename)
primary_key_length:lengthofthekeycolumninDBrepresentedasavarchar(defaultto255)
max_lo:maxlowvaluebeforeincreasinghi(defaulttoShort.MAX_VALUE)
使用这个类的优点就是:
可移植性好,
如果系统一般不重启,而且需要用此表建立大量的主键,可以吧max_lo配置大一点,这样可以减少读取数据表的次数,提高效率;反之,如果服务器经常重启,可以吧max_lo配置小一点,可以避免每次重启主键之间的间隔太大,造成主键值主键不连贯。
注意:
在我测试时抛出了一个异常,在网上找不到相关的信息,最后认真分析了下原代码及错误信息提示,发现可能是hibernate的dialet出错了,异常如下:
2011-03-22 21:22:00,479 [main] ERROR org.hibernate.id.MultipleHiLoPerTableGenerator - could not read or init a hi value com.microsoft.sqlserver.jdbc.SQLServerException: Line 1: FOR UPDATE clause allowed only for DECLARE CURSOR. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(Unknown Source) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(Unknown Source) at org.hibernate.id.MultipleHiLoPerTableGenerator.doWorkInCurrentTransaction(MultipleHiLoPerTableGenerator.java:135) at org.hibernate.engine.TransactionHelper$1Work.doWork(TransactionHelper.java:38) at org.hibernate.engine.transaction.Isolater$JdbcDelegate.delegateWork(Isolater.java:187) at org.hibernate.engine.transaction.Isolater.doIsolatedWork(Isolater.java:43) at org.hibernate.engine.TransactionHelper.doWorkInNewTransaction(TransactionHelper.java:51) at org.hibernate.id.MultipleHiLoPerTableGenerator.generate(MultipleHiLoPerTableGenerator.java:189) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:99) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:686) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:1) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683) at com.radicasys.intimate.segment.dao.impl.IntimateListBeanDaoImpl.save(IntimateListBeanDaoImpl.java:46) at com.radicasys.intimate.segment.dao.IntimateListBeanDaoTest.save(IntimateListBeanDaoTest.java:95) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:592) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 2011-03-22 21:22:00,482 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Line 1: FOR UPDATE clause allowed only for DECLARE CURSOR.
因为我用的是MSSQL2005,但测试时用的是MYSQL的dialet,所以抛出如下异常,改过后主没问题了。