java - How to avoid persisting new object when oneToMany connection? -


enter image description here

there 3 lines in returnreason-table , don't want more lines there. user choose 1 of 3 reasons , want id rma-table. inserts new line reason-table every time when inserting new rma. can take relation off between tables wonder if there better solution avoid inserting new lines when persisting rma object? if take cascadetype off class rma, not helping/working. got error message, jpa found object, not persisted or that.

errormessage if took cascadetype.all off

java.lang.illegalstateexception: during synchronization new object found through relationship not marked cascade persist: com.entity.returnreason[ returnreasonid=null ].

public class rma implements serializable { @manytoone(cascade = cascadetype.all) private returnreason returnreasonreturnreasonid;  public class returnreason implements serializable { @onetomany(mappedby = "returnreasonreturnreasonid", cascade = cascadetype.all) private collection<rma> rmacollection; 

jpa methods require model use managed entities, while seem attempting associate managed entity outside context. bad practice, , jpa required throw exceptions cannot tell intend unmanaged instance.

you have 2 options

  1. read in 3 returnreason , use entities merging. if there ever 3, can change caching options in cache, em.find operation doesn't have hit database.
  2. remove mapping in rma class returnreason class , map returnreasonreturnreasonid field basic mapping. can set value in rma entity directly

the first option used, , required since should have been maintaining returnreason rmacollection anyway everytime add new rma instance. while may seem need set rma.returnreasonreturnreasonid, these java objects, , application responsible maintaining both sides of bidirectional relationships.


Comments