Aleksandar Lucic
Aleksandar Lucic

Reputation: 37

Getting id after inserting row(Spring boot/JPA)

I have trouble with getting id from one table after a new user is added.

I have 2 tables, the user and the other one that has to be joined with the user table into the third table which will contain id from those 2 tables.

For that, I need the id of the second table, which if I understood correctly have to be collected after inserting row.

How to implement that getting id?

Upvotes: 1

Views: 8400

Answers (2)

Vipin CP
Vipin CP

Reputation: 3797

Try:

retObject = repository.save(retObject );
repository.flush();
retObject.getId(); // get id here

Upvotes: 4

Andrzej Jaromin
Andrzej Jaromin

Reputation: 269

You have to define relationship between two entities using @OneToMany and @ManyToOne annotations. Then calling save method from JpaRepository on the "one" side will set it's id. Then you just call the save method on the "many" side of relation, and related id will be inserted along with the data. Or, instead of calling save on every entity separately, you can set the attribute cascade=CascadeType.ALL of @OneToMany annotation and then you'll have to call save method only on one entity.

Upvotes: 1

Related Questions