How do I use a sequence in Hibernate XML mappings?
The documentation mentions the <generator>
e开发者_如何学JAVAlement. However, I want the sequence to be a column instead of an ID.
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.
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>
精彩评论