What is the difference between EntityManager.find() and EntityManger.getReference()?

后端 未结 3 1365
余生分开走
余生分开走 2020-12-02 06:35

Whats is the difference between

 T EntityManager.find(Class entityClass, Object primaryKey) and 
 T EntityManager.getReference(Cl         


        
3条回答
  •  借酒劲吻你
    2020-12-02 07:37

    The book Beginning Java EE 6 Platform with GlassFish 3, mention the differences in page 135: "Finding By ID"

    find() if the entity is found, it is returned; if it is not found, a null value is returned.

    MyEntity obj = em.find(MyEntity.class, id);
    if(obj != null){
       // Process the object 
    }
    

    getReference() is intended for situations where a managed entity instance is needed, but no data, other than potentially the entity's primary key, being accessed.

    try {
        MyEntity obj = em.getReference(MyEntity.class, id);
        // Process the object
    } catch (EntityNotFoundException e) {
        // Entity Not Found
    }
    

提交回复
热议问题