JPA SequenceGenerator

时间:2013-01-05 17:16:11

标签: java postgresql jpa sequence

实体类

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "generator1")
@SequenceGenerator(sequenceName = "sequence2", name = "generator1",
allocationSize = 1, initialValue = 1)
private int                id;

主要

EntityManagerFactory emf = Persistence.createEntityManagerFactory("Employee");
                entityManager = emf.createEntityManager();
                 Employee us = new Employee();
                us.setFirstname("John");
                us.setLastname("John");
                entityManager.getTransaction().begin();
                entityManager.persist(us);
                entityManager.getTransaction().commit();

第一个身份证号码是1,但是当我再次运行它时会创建一个身份证号码3(它应该是2?),我不知道为什么。这有什么不对?

1 个答案:

答案 0 :(得分:2)

使用Postgres时,此行为符合逻辑。 由于最小(和默认)缓存大小为1,因此当您插入标识为1的实体时,它会预取2

Postgres手册的9.16. Sequence Manipulation Functions部分表明:

Important: To avoid blocking concurrent transactions that obtain numbers from the same sequence, a nextval operation is never rolled back; that is, once a value has been fetched it is considered used, even if the transaction that did the nextval later aborts. This means that aborted transactions might leave unused "holes" in the sequence of assigned values.

这意味着,如果您获取2并最终不使用它,则不会重复使用它。

这就是为什么你在3后看到1

无论如何,您应该记住,如此低的缓存大小会对性能产生影响,因此不建议这样做。