문제

I'm using JPA and when I insert data into the database my ID is autoincremented with 50. I'm using persistence.GeneratedValue to autoincrement it:

This is how my model/entity class looks like (Entity to be inserted):

..imports
@Entity
public class Example extends Identifiable  {
   ..
}

Identifiable :

..imports
@MappedSuperclass
public abstract class Identifiable {
    @Id @GeneratedValue protected long id;
    ..
}

Database:

#    ID    NAME    ...
1    701   a
2    751   b
3    801   c

Anyone have an Idea what the problem is?

도움이 되었습니까?

해결책

Default value for GeneratedValue.strategy is GenerationType.AUTO. What this means is spelled out nicely in JPA 2 specification:

The AUTO value indicates that the persistence provider should pick an appropriate strategy for the particular database. The AUTO generation strategy may expect a database resource to exist, or it may attempt to create one. A vendor may provide documentation on how to create such resources in the event that it does not support schema generation or cannot create the schema resource at runtime.

For both TableGenerator and SequenceGenerator default value of allocationSize is 50. This means that chunk of 50 values is reserved. In shutdown there reserved values will be gone. If application is shutdown after only one is used, values from 2 to 50 are gone and next time 51 to 100 will be reserved. Strategy other than auto should be used if more control over identifier generation is needed. That can be done for example as follows:

@TableGenerator(
  name = "yourTableGenerator"
  allocationSize = 1,
  initialValue = 1)
@Id 
@GeneratedValue(
  strategy=GenerationType.TABLE, 
  generator="yourTableGenerator")

or:

@SequenceGenerator(name="yourSequenceGenerator", allocationSize=1)
@Id 
@GeneratedValue(strategy=GenerationType.SEQUENCE, 
                generator="yourSequenceGenerator")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top