java - Spring/Hibernate persisting entity with nested entity (by nested entity id / primary key only) -
using spring 4.1.7 , hibernate 4.3.10.
i trying create new custom note object via form post spring controller. note object contains book object, , both note , book persisted using using hibernate.
the controller class form posts to:
@controller @requestmapping(value = "/notes") public class noterestcontroller { [...] @requestmapping(value = "/create", method = requestmethod.post) public modelandview createforview(final model model, @modelattribute final note note) { /*-- debug. works, not ideal. { final book validbook = daoservice.retrievebook(note.getbook() .getid()); note.setbook(validbook); }//*/ uuid creatednoteid = daoservice.createnote(note); model.addattribute("note", daoservice.retrievenote(creatednoteid)); return new modelandview("note/note"); } } the note object:
@entity @table(name = "note") public class note { @id @column(name = "id", insertable = false, updatable = false) @generatedvalue(generator = "uuid") @genericgenerator(name = "uuid", strategy = "uuid2") @type(type = "pg-uuid") private uuid id; @column(name = "title") private string title; @manytoone(cascade = cascadetype.all) @joincolumn(name = "book", referencedcolumnname = "id") private book book; [...] } the book object:
@entity @table(name = "book") public class book { @id @column(name = "id", insertable = false, updatable = false) @generatedvalue(generator = "uuid") @genericgenerator(name = "uuid", strategy = "uuid2") @type(type = "pg-uuid") private uuid id; @column(name = "name") private string name; [...] } the underlying database (currently postgres 9.1) defines book.name column not null.
what want use spring forms create new note passing in unique id of book (and note title string).
my test html form (page formatting removed brevity):
<form:form method="post" id="create" action="/notes/create" commandname="note"> <form:input type="text" id="title" name="title" path="title" /> <form:input type="text" id="book.id" name="book.id" path="book.id" value="" /> <input value="create" type="submit" name="create"> </form:form> when submit form (with valid value in book.id), controller creates book instance in note id set, null name field. understandable, since don't pass in, nor want pass in every time.
when submit form debug block commented out, exception thrown regarding null name field. however, if uncomment debug block (which prefetches book , sets note instance) works.
is there better way can without manually fetching nested objects? ultimately, intend have more entities within note , don't want have fetch them before creating note.
i hope makes sense!
Comments
Post a Comment