Hibernate Annotations - Which is better, field or property access?

后端 未结 25 1221
说谎
说谎 2020-11-22 15:02

This question is somewhat related to Hibernate Annotation Placement Question.

But I want to know which is better? Access via properties or access vi

25条回答
  •  孤街浪徒
    2020-11-22 15:26

    I believe property access vs. field access is subtly different with regards to lazy initialisation.

    Consider the following mappings for 2 basic beans:

    
      
        
          
        
        
      
    
    
    
      
        
          
        
        
      
    
    

    And the following unit tests:

    @Test
    public void testFieldBean() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        FieldBean fb = new FieldBean("field");
        Long id = (Long) session.save(fb);
        tx.commit();
        session.close();
    
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        fb = (FieldBean) session.load(FieldBean.class, id);
        System.out.println(fb.getId());
        tx.commit();
        session.close();
    }
    
    @Test
    public void testPropBean() {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        PropBean pb = new PropBean("prop");
        Long id = (Long) session.save(pb);
        tx.commit();
        session.close();
    
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        pb = (PropBean) session.load(PropBean.class, id);
        System.out.println(pb.getId());
        tx.commit();
        session.close();
    }
    

    You will see the subtle difference in the selects required:

    Hibernate: 
        call next value for hibernate_sequence
    Hibernate: 
        insert 
        into
            FIELD_BEAN
            (message, id) 
        values
            (?, ?)
    Hibernate: 
        select
            fieldbean0_.id as id1_0_,
            fieldbean0_.message as message1_0_ 
        from
            FIELD_BEAN fieldbean0_ 
        where
            fieldbean0_.id=?
    0
    Hibernate: 
        call next value for hibernate_sequence
    Hibernate: 
        insert 
        into
            PROP_BEAN
            (message, id) 
        values
            (?, ?)
    1
    

    That is, calling fb.getId() requires a select, whereas pb.getId() does not.

提交回复
热议问题