java hibernate entity: allow to set related object both by id and object itself

前端 未结 3 1390
野趣味
野趣味 2021-02-05 17:18

I\'ve got a following Java class which is also a Hibernate entity:

@Entity
@Table(name = \"category\")
public class Category {

    @ManyToOne
    @JoinColumn(na         


        
3条回答
  •  [愿得一人]
    2021-02-05 18:17

    Hibernate provides a method called (quite confusingly) Session.load() for this scenario.

    Session.load() returns a lazy proxy with the given identifier without querying the database (if object with the given identifier is already loaded in the current Session, it returns an object itself).

    You can use that proxy to initialize relationships in your entities being saved:

    category.setParent(session.load(Category.class, parent_id));
    

    Note that this code doesn't check existence of Category with the given id. However, if you have a foreign key constraint in your DB schema, you'll get a constraint violation error when invalid id is passed in.

    JPA equivalent of this method is called EntityManager.getReference().

提交回复
热议问题