问题
How do I use a sequence in Hibernate XML mappings?
The documentation mentions the <generator>
element. However, I want the sequence to be a column instead of an ID.
回答1:
I know when using Hibernate with Oracle the id in the mapping file is defined something like:
<id name="id" column="item_id">
<generator class="sequence">
<param name="sequence">NAME_OF_YOUR_SEQUENCE</param>
</generator>
</id>
You can also specify the generator class as "native", which is handy if you then switch to an auto incrementing RDMS such as MySQL. The sequence bit is then ignored in MySQL.
Edit: Just re-read your question. I don't think hibernate handles sequences on non-id columns. The general approach I have seen is adding triggers to the table, but it's not a nice solution.
回答2:
If you use a individual Oracle sequence, Hibernate will query the DB for the next value first, and then perform the insert (unless you use an optimisation strategy to grab a chunk of them).
You can consolidate those two executions into one by retrieving the value that oracle assigned on input by adjusting your hibernate xml file to include the following property:
<property name="hibernateProperties">
<props>
...
<prop key="hibernate.jdbc.use_get_generated_keys">true</prop>
...
</props>
And using sequence-identity on your column
<generator class="sequence-identity">
<param name="sequence">SEQ_NAME</param>
</generator>
来源:https://stackoverflow.com/questions/5082175/how-to-use-sequence-in-hibernate-as-a-property-in-xml-mapping