简体   繁体   中英

exception while persist the JPA object

I have made an entity class and add the annotation @id and @GeneratedValue on ID field. While persisting the object I was wondering it will automatically set the value in ID field but when commit the data into db I got sequence exception. Then I had set the ID and persist it will commit successfully.

I have ran my code again and try to persist the data with the same values and I got exception related to the duplication..

I have searched and change my @GeneratedValue annotation with the following:

@SequenceGenerator(name= "seq",sequenceName="seq")
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq")

and the data is persist successfully without setting the ID value manually.

So my question is what is the diffrenece between @GeneratedValue and @SequenceGenerator ain't these two annotation used for the same purpose? and how can we use the strategy in the attribute?

Please guide me.Help will be appreciated Thanks

I found this may help you. From the Javadoc for SequenceGenerator

Defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation. A sequence generator may be specified on the entity class or on the primary key field or property. The scope of the generator name is global to the persistence unit (across all generator types).

I will try to cover your 2 questions in one shot.

@SequenceGenerator is used for point to the sequence you created in the DB with the ' sequenceName ' property and then you give it a name with the ' name ' property. Example:

 @SequenceGenerator( name="myIdSeq", sequenceName="MY_ID_SEQ", allocationSize=1, initialValue=1 )
 @GeneratedValue( strategy=GenerationType.SEQUENCE, generator="myIdSeq" )

One note this name can be shared across your persistence unit.




@GeneratedValue defines what strategy you want the ID to be generated, typically we have stategies like

1. IDENTITY(AUTO) which will auto increment and is popular in MySQL

2. SEQUENCE which points to a sequence Gernerator and is the one you use above. Note the generator value should match the name value in the @ SequenceGenerator

3. TABLE which uses a dedicated table to stores the sequence name with column for running numbers and is suitable for enterprise level app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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