hibernate - how to save parent with detached child

前端 未结 2 2069
难免孤独
难免孤独 2020-12-19 08:29

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.

<         


        
相关标签:
2条回答
  • 2020-12-19 09:22

    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.

    0 讨论(0)
  • 2020-12-19 09:30

    You have to decide how do you want to persist ChildEntity with ParentEntity.

    1. 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);
      
    2. 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.

    0 讨论(0)
提交回复
热议问题