Manually specify the value of a primary key in JPA @GeneratedValue column

后端 未结 6 1144
眼角桃花
眼角桃花 2020-12-29 02:42

I\'m having an Entity which has a primary key / id field like the following:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
         


        
6条回答
  •  半阙折子戏
    2020-12-29 03:13

    Using GenerationType.SEQUENCE with PostgreSQL and EclipseLink worked for me.

    1) Change

    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    

    by

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

    Now, you can call sequence using NativeQuery:

    return ((Vector) em.createNativeQuery("select nextval('step_id_seq')::int").getSingleResult()).get(0);
    

    and set the returned Id to your Entity before call EntityManager.persist() method.

    Hope it's not too late!

提交回复
热议问题