1

实体类

@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();

第一个 ID 号是 1,但是当我再次运行它时,它会创建一个 ID 号 3(应该是 2?),我不知道为什么。这里有什么问题?

4

1 回答 1

2

当您使用Postgres. 由于最小(和默认)缓存大小是1,当您插入具有 id 的实体时,1它 prefetch 2

9.16 节。Postgres 手册的序列操作函数指出:

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并最终不使用它,它将不会被重用。

这就是为什么你看到31

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

于 2013-01-05T18:04:47.307 回答