使用GenerationType.SEQUENCE生成负Id值

时间:2017-12-07 11:22:20

标签: java postgresql jpa entity sequences

为什么我总是得到实体ID的负值?它与increment金额值有关吗?例如,当我使用

create sequence message_sequence start 1 increment 1;

我总是得到负值(-38,-44,-45)。但是如果我放

create sequence message_sequence start 1 increment 50;

一切都很好(52,102)。为什么这么奇怪的行为? 这是一个实体:

@Entity
@Table(name = "messages")
public class Message {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "message_sequence")
    @SequenceGenerator(name = "message_sequence", sequenceName = "message_sequence")
    private long id;

    private String text;

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

程序入口点:

EntityManagerFactory emf = JPAUtility.getEntityManagerFactory();

EntityManager entityManager = emf.createEntityManager();

entityManager.getTransaction().begin();

Message m = new Message();
m.setText("Hello World");

etityManager.persist(m);

entityManager.getTransaction().commit();
entityManager.close();

2 个答案:

答案 0 :(得分:2)

SequenceGenerator批注中有一个名为allocationSize的变量。默认情况下,此大小为50。这意味着Hibernate将保留50个id,并且不需要为每个插入都检索新的id。设置allocationSize = 1可以解决此问题,以产生新的价值。

答案 1 :(得分:1)

sqlcmd -S $DB_HOST -U $DB_USER -P $DB_PASSWORD -o $mssqlresult -s "," -W -h -1 -Q "SET NOCOUNT ON SELECT \ TRANS_TYPE AS "ACTION TYPE",\ ORDER_ID AS "ORDER ID",\ EXEC_ID AS "EXECUTION ID",\ ACC_ID AS "ACCOUNT ID",\ TRAD_ID AS "TRADER ID",\ DIRECTION AS "SIDE",\ PP AS "PRICE",\ QUANT AS "QUANTITY",\ UDATE AS "UTC DATE TIME",\ LDATE AS "LOCAL DATE TIME"\ FROM [CDB].[CDS].[V_DART_TRANS]\ WHERE CAST(UDATE AS DATE)='$trade_date'; 代码添加到 allocationSize = 1 后 工作正常!