Skip to content
Advertisement

how do i save a new student that contains entities, but don’t create these entities because they already exist in the database?

I want to save a student and a student has a TargetAudience object as an attribute. These target audiences are allready hardcoded in my database. (targetaudience = campus + major). Now when i post like this:

it doesnt work because everythime it creates a new object for the campus and because i use name as a primary key it throws an exception. Shouldn’t spring data jpa look if the entity allready exists and then use that instead? Or how can i make it do this?

Sorry if this isn’t clear, it’s my first time posting

student.java:

StudentController.java

StudentService.java:

TargetAudience.java:

Campus.java:

Advertisement

Answer

What exception are you facing while trying to save? A stack trace would’ve been more helpful. However, you can work around this in two ways

Either, If you want to avoid saving TargetAudience altogether, you can annotate the TargetAudience property in @Transient annotation so, it’ll not be considered for database saving.

Or, JPA is trying to save the object with new primary key every-time because the object is in detached state (if your JPA provider is hibernate, which is default JPA provider). You should modify registerStudent() method in StudentService like –

So, you’re explicitly fetching TargetAudience from database and setting it to student object you’re getting. In this way, fetched targetAudience will be in persistent state (not detached) and it’ll not try to assign new primary key again.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement