drunkenfist
drunkenfist

Reputation: 3038

Get identity value before saving in JPA

I have a database with an auto-generated primary key. The corresponding JPA entry is below:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
@JsonProperty("item_id")
private Long id;

Now, I have another String field to which I need to append the id before inserting it into the DB. Is it possible to get the identity value before inserting the value into the database? I saw on some posts that I can flush the entity. But I'm not sure if that would work in my scenario. I'm new to JPA, so I don't know the effects of doing a flush.

Thanks.

Upvotes: 1

Views: 923

Answers (1)

serg.nechaev
serg.nechaev

Reputation: 1321

I don't think you can. The generated key comes back from DB as part of the statement doing the INSERT operation. Even the retrieval of the generated keys is implementation-specific and is not guaranteed on every storage.

Upvotes: 2

Related Questions