Sleep mode - how to save a parent with an individual child

I am sending an object from the user interface. This object will be created with reference to an existing child.

This is a simple illustration for this relationship.

class ParentEntity { @Id Long id; @ManyToOne(fetch = FetchType.LAZY) private ChildEntity child; } class ChildEntity { @Id Long id; } ChildEntity child = new ChildEntity(); child.setId(1); //parentEntity is created based on data sent from UI parentEntity.setChild(child); 

When I save this object, Hibernate gives me "org.hibernate.TransientPropertyValueException: the object refers to an unsaved transient instance."

I do not need to save the child, because I do not change the child at all. Just need to save the child id in the parent table.

I tried to use several CascadeType, but none of them worked.

+4
source share
2 answers

Just use a proxy for the child:

 parentEntity.setChild(entityManager.getReference(ChildEntity.class, childId)); 

Here you need to use EntityManager.getReference :

Get an instance whose state can be lazily retrieved.

Hibernate will create a proxy containing only the identifier without accessing the database.

+6
source

You need to decide how you want to save ChildEntity with ParentEntity.

  • If you always want to save the child only by id, then you can do it, and FK will block you if its an invalid child.

     class ParentEntity { @Id Long id; //To directly load/insert/update childId only @Column("child_id") private Long childId; // To load the child entity with parent, Note that insertable/updatable MUST be false // as we are inserting/updating = true by default on childId column mapping @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "child_id", insertable = false, updatable = false) private ChildEntity child; } parentEntity.setChildId(childId); 
  • But if you want to save the child using the existing model, where the child is displayed as an object, you need to take the child and install it. parentEntity.setChild (childRepository.findOne (childId)); or you can also write your own DAO method for getOrCreateChild, which can create a new child or find an existing one and return it so that you can transfer it first.

In your case, when you use the new keyword to create childEntity, hibernate will always consider it disconnected and try to keep it.

+2
source

Source: https://habr.com/ru/post/1245164/


All Articles