Home > OS >  Parent child issue hibernate jpa
Parent child issue hibernate jpa

Time:08-05

Consider I have 2 entity

@Entity(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long id;

    @OneToMany(cascade = CascadeType.ALL)
    public List<Child> children = new ArrayList<>();

}

and

@Entity
class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long id;
    
    @ManyToOne
    public Parent parent;
}

how can I create Child instance with parentId without call findById(Long parentId) i.e.

Child createChild(parentId) {
Child child = new Child();
child.parent = //parent.findById(parentId); I don't wanna go to database 
//for nothing if in this spot anyway will be parentId in database
return child;
}

I thought it can be done with quare but hql don't have INSERT .... VALUE .., so I'm here, appreciate any help.

If it's don't have any sense due to architecture, please explain, it's be a great help.

CodePudding user response:

It is not a big problem that you will call parent.findById(parentId); Hibernate caches some of the requests especially when used findById. You can see this answer link

The only thing to note is that you should not override findById in the repository, or if you do you should added it to the jpa cache.

CodePudding user response:

No need to create new object in

public List<Child> children = new ArrayList<>();

just write

@OneToMany(targetEntity = Child.class, cascade = CascadeType.ALL)
public List<Child> children;

CodePudding user response:

EntityManager#getReference(Class<T> entityClass, Object primaryKey) is your friend here.

entityManager.getReference(Parent.class, parentId); returns an entity proxy. It can be used to improve the performance of the write operations since there will be no database call unless you access the fields of the returned entity.

  • Related