I am sending an object from UI. This object is going to be created with a reference to an existing child.
This is simple illustration for this relation.
<
Just use the proxy for the child:
parentEntity.setChild(entityManager.getReference(ChildEntity.class, childId));
The point here is to use EntityManager.getReference:
Get an instance, whose state may be lazily fetched.
Hibernate will create the proxy containing only the id without going to the database.
You have to decide how do you want to persist ChildEntity with ParentEntity.
If you always want to persist child only by id then you can do like this and FK will block you if its 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 persist child using your existing model where child is mapped as an object, then you have to fetch the child and set it. parentEntity.setChild(childRepository.findOne(childId)); or you can also write a custom DAO method for getOrCreateChild which can create a new child or find existing one and return it so that you can persist child first.
In your case when you use new keyword for creating childEntity, hibernate will always consider it as detached and tries to persist.