简体   繁体   English

休眠:更新表生成器

[英]Hibernate: Update table generator

Is there a way to tell Hibernate to first check if the current primary key generated by a Table Generator is usable or outdated? 有没有办法告诉Hibernate首先检查表生成器生成的当前主键是否可用或过时?

I have an application which uses hibernate to create new entries in several tables in my database, but sometimes these generated values are outdated and already used. 我有一个使用hibernate在数据库的几个表中创建新条目的应用程序,但是有时这些生成的值已经过时并且已经被使用。 This happens because this database is used by quite a few applications and scripts, and some of these use the "select MAX(ID)+1"-Keygeneration"strategy". 之所以会发生这种情况,是因为许多应用程序和脚本都使用了该数据库,其中一些使用了“选择MAX(ID)+1”-“密钥生成”策略。 It is not really an option to change all other components to use the table generator (although it would solve the problem), so I have to make sure that the values I get from the table generator are really usable. 更改所有其他组件以使用表生成器实际上不是一个选择(尽管它可以解决问题),所以我必须确保从表生成器获取的值确实可用。

Is there any way to tell Hibernate to check the validity of the generated values before it tries to insert a new record into the database (and throw a ConstraintViolationException)? 有没有办法告诉Hibernate在尝试向数据库中插入新记录(并抛出ConstraintViolationException)之前检查生成的值的有效性? Or, alternatively, is there a way to manually update the generator tables before hibernate uses them to generate new Ids? 或者,是否有一种方法可以在hibernate使用生成器表生成新ID之前手动对其进行更新?

The obvious way would be to run a native query like UPDATE pk_generator SET value=(SELECT MAX(ID)+1 from members) WHERE column='members' 最明显的方法是运行一个本地查询,例如UPDATE pk_generator SET value=(SELECT MAX(ID)+1 from members) WHERE column='members'

When you save a object with saveOrUpdate() the objects id field will get updated with the auto generated id if it was a create operation. 当您使用saveOrUpdate()保存对象时,如果是创建操作,则将使用自动生成的ID更新对象ID字段。 So that it will never conflict with id which was already generated and used. 这样它就不会与已经生成和使用的id冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM