user1211530 user1211530 - 2 months ago 6x
Java Question

When using the @SequenceGenerator/@GeneratedValue in JPA - is a database trigger redundant/unnecessary?

I saw this post (JPA Entity Lifecycle Events vs database trigger), but it didn't ask quite as explicitly as I am here:

Am I required to have a sequence AND a trigger for when I insert a row with a PK with a value of (null)?

Or will JPA somehow interpret the sequence annotations as a signal to grab .nextVal?


If you define a sequence on your primary key (@Id annotated field) and you map the sequence using the annotations @GeneratedValue and @SequenceGenerator, you can persist an entity with a null primary key. JPA will automatically call the sequence to get the next value (or get it from its cache). The primary key declaration should look like.

@Column(name = "TABLE_PK")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE_GENERATOR_NAME")
@SequenceGenerator(name = "SEQUENCE_GENERATOR", sequenceName = "SEQUENCE_NAME")
private Integer id;