问题
I want any generated primary keys in my database to be negative integers.
I defined a TableGenerator:
<table-generator name="MY_SEQ" table="MY_SEQUENCE_TABLE"
initial-value="-1000000" allocation-size="1" />
I assumed this would start the first generated key at -1000000 and increment each id by 1. So the next id would be -999999.
When I create and persist a new entity I get the following error:
java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint...
When I check the MY_SEQUENCE_TABLE the value in the SEQUENCE_NEXT_HIGH_VALUE is 2. I tried defining the table generator in the ORM.xml and as an annotation but the behavior is the same both ways.
Is it possible to use negative values for PKs in Hibernate?
Thanks
Update
I am doing this because I am moving data from one database to another. Then I am moving the data back. During this time new entities can get created in the other database (Derby). When I move the entities back I need a way to tell if they were created on that database without changing the table schema. I figured I would check the ids for negative values and they way I know that have to be created as new entities when I move the data back.
Does anyone know what Hibernate class generates handles the TableGenerator and generates the Table code for the sequence?
Update 2
After some testing it seems that Hibernate ignores initial-value and allocation-size when using table-generator.
I added this property to the persistence.xml
<property name="hibernate.id.new_generator_mappings" value="true"/>
I switched to a sequence generator and initial-value is properly used but allocation-size is not saved as a negative. According to the Derby spec a negative sequence is valid.
From the 10.6 reference:
If specified, the INCREMENT value is a non-zero number which fits in a DataType value. If not specified, the INCREMENT defaults to 1. INCREMENT is the step by which the sequence generator advances. If INCREMENT is positive, the sequence numbers get larger over time. If INCREMENT is negative, the sequence numbers get smaller.
Off to try more things.....
回答1:
I took a look at JPA specification and there doesn't seem to be anything related to constraints regarding initial value, so this is probably implementation dependent. Meaning: you shouldn't use negative initial values if you want standards compliance.
Have you tried setting allocation-size ="-1"
? I cannot try this out right now, but I'm curious how does Hibernate behave since databases can have negative sequence numbers.
来源:https://stackoverflow.com/questions/4993683/jpa-hibernate-derby-tablegenerator-use-negative-values