i have following simple example. when runs, see quoterequest object being generated auto-generated id. next, see accidents object being generated, quote_request_id that's being inserted null, error:
column 'quote_request_id' cannot null
@entity @table(name = "quotes") public class quoterequest { public quoterequest(){} @id @column(name = "quote_request_id") @generatedvalue(strategy = generationtype.identity) private long quoterequestid; @onetomany(mappedby = "quoterequest", cascade = cascadetype.all) @ordercolumn(name = "accidents_id") private accidents[] accidents; // getters , setters } @entity @table(name = "accidents") public class accidents { public accidents() { } @id @generatedvalue(strategy = generationtype.identity) @column(name = "accidents_id") private long accidentid; @column(name = "amount", nullable = false) private float amount; @manytoone(optional = false, cascade = cascadetype.all) @joincolumn(name = "quote_request_id", nullable = false) private quoterequest quoterequest; // getters , setters }
why isn't inserting newly generated id accidents column?
when creating accidents, don't set quoterequest property. should doing that? need have bi-directional relationship?
this reason.
first, "do need have bi-directional relationship?". well, 1 can tell. however, having bi-directional relationship. way set up, accident
side owning relationship. means, db column accident.quote_req_id
relying on field accident.quoterequest
. have not populate field, hibernate assuming null. hence inserting null. expected behavior.
in short, should make sure quoterequest.accident
, accident.quoterequest
consistent, example:
class quoterequest { private list<accident> accidents; // prefer list or set public void setaccidents(list<accident> accidents) { this.accidents = new arraylist<>(accidents); (accident accident:accidents) { accident.setquoterequest(this); } } } class accident { private quoterequest quoterequest; public setquoterequest(quoterequest quoterequest) { // there more... this.quoterequest = quoterequest; } }
this basic example on like. in short, need accident.quoterequest
set appropriate value. there still lots of issue in above implementation , leave (e.g. when has accidents
set , replaced list)
Comments
Post a Comment