chris
chris

Reputation: 937

[Hibernate]Merge transient object with childrens

I've some probleme with merge. My update method works in this way:

void update(Parent parent) {
    evict(parent);
    merge(parent);
}

My classes:

Parent {

  Long id;

  List<Children> childrens;

  @OneToMany(targetEntity =ChildrenImpl.class, fetch=FetchType.LAZY)
  @JoinColumn(name="PARENT")
  @org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
  List<Children> getChildrens(){...}

  @Id
  Long getId() {...}

}



Children{

  Parent parent;

  @ManyToOne(targetEntity = ParentImpl.class, fetch = FetchType.LAZY)
  @org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
  @JoinColumn(name = "PARENT", nullable = false)
  Parent getParent(){...}

}

When i create a new Parent(transient) object and add new childrens and trying updated(evict & merge) then logs show me this after flush hibernate session:

INSERT PARENT //everythings here is ok.

INSERT CHILDREN // but without parent id(id=null)

Order is good but children doesn't have parent id in insert. Everything works fine when Parent is persisted in database, then childrens always have a good id.

Any ideas what should I do to get id from transient object(from persisted is ok).

Regards KZ.

Upvotes: 3

Views: 2021

Answers (1)

hvgotcodes
hvgotcodes

Reputation: 120198

You cannot get an id from a transient object, by definition a transient object does not have an id.

why are you doing a merge if you create a new object? When you create a new object, you should save it. If you change the values of an existing object, you should update it. You should be merging only if an object that was persistent becomes detached, and you need to reattach it.

Upvotes: 2

Related Questions