hibernate - Properly cascading this @OneToMany relationship (Spring Data JPA) -


alright, i'm little deperate right now. i've read many of other related questions hasn't helped me resolve issue yet. i'll glad if can me out.

i'm using spring data jpa , have these 2 entities:


device.class

private string id;  @onetomany(mappedby = "device", cascade = cascadetype.all) @jsonignore @restresource(exported = false) private list<reading> readings; 

reading.class

@manytoone(cascade = {cascadetype.merge}) /*this isn't right...*/ @joincolumn(name = "device_id") private device device; 

expectation

i'm saving readings , expect device cascaded correctly (persisted or merged), depending on whether exists. (readings inserted once, never updated)

reality

i can make work partially:

when use cascade = cascadetype.all or cascade = cascadetype.persist can save first reading , mapped device. once insert second reading has relationship same device, along lines of:

duplicate entry '457129' key 'primary' ('457129' = reading.device.id) 

as understand, second reading entity tries cascade device inserting new row instead of updating existing one.

i can "work around" using cascade = cascadetype.merge instead. device updated correctly when save new reading existing device entity. but can no longer cascade device doesn't yet exist!

column 'device_id' cannot null  (reading.device_id) 

the save

i receive json dto's , create entities it.

pseudocode:

reading reading = deserialize(jsonreading); device device = deserialize(device);  reading.setdevice(device); /* device entity detached */  readingservice.save(reading); 

i guess part of problem might have me setting detached entity?

what doing wrong? realtionships bad? happening? need manage these transactions manually?

thank you!

the @onetomany association definition parent association, if it’s unidirectional or bidirectional one. parent side of association makes sense cascade entity state transitions children. (source: hibernate docs).

based on documentation remove cascade device field. docs contains code examples storing phone , person @onetomany , @manytoone may try.

as didn't post code saving part suppose set device before saving reading as

reading.setdevice(device); readingdao.save(reading); // depends on implementation 

when persisting reading object device should saved automatically.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -