Skip to content
Advertisement

Hibernate simply adding elements to manytomany from JSON

I want to add elements in my manytomany association via a request without loading each added element. I am using a custom join table. [Code will be added at the bottom]

So for example this is the JSON I get:

JavaScript

So there is one HomeworkMaterial. If I send this as POST to the server nothing happens (as expected). For all following examples, I’m just using homeworkRepository.save(homework)

Also the following will work. (All HomeworkMaterials will be removed as expected)

JavaScript

But if I want to add elements to the materials like this:

JavaScript

There will be an error.

attempted to assign id from null one-to-one property [schooling.api.courses.homework.ids.HomeworkMaterial.homework]

So the problem is, that the materials are not loaded from the DB and I have just the ID of HomeworkMaterial. So I am pretty sure that if I just loop through the HomeworkMaterials and load all the Materials from the DB it works. But this is really not a good solution in my opinion, because I think I should not need to access the DB for adding those HomeworkMaterials since I did this on the client and have the IDs of the materials and if something is wrong there would be just an exception thrown.

So my question is, how can I easily save more HomeworkMaterials without having the materials fetched?

I have also tried looping through them and saving them in their own repository, but this does not work too. (got the same exception as with the previous approach)

So now my Code:

Homework.java

JavaScript

Material.java

JavaScript

HomeworkMaterial.java

JavaScript

HomeworkMaterialId.java

JavaScript

As said above, for saving I’m just simply using homeworkRepository.save(homework)

Advertisement

Answer

I found a solution to this, I can just “fetch” the Homework and Material with getById so the DB is not accessed, but I have a reference to them and I can then save it.

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