Just getting id column value not using join in hibernate object one to many relation

前端 未结 3 903
南笙
南笙 2020-12-06 19:43

I\'m using hibernate 4+.

I have two sample tables.

Table A

public class A {
  @Id
  private int id;

  @OneToMany(fetch=LAZY)
  private List&         


        
3条回答
  •  粉色の甜心
    2020-12-06 20:20

    Yes, because proxies contain the id anyway. To get the id of an A proxy without initializing it, first declare the id to be accessed via property:

    @Entity
    public class A {
      @Id
      @Access(AccessType.PROPERTY)
      private int id;
    
      @OneToMany(fetch=LAZY)
      private List list;
    
      public int getId() {
        return id;
      }
    
      public void setId(int id) {
        this.id = id;
      }
    }
    

    Then, just read the id:

    b.getA().getId();
    

    Changing access type for the id is necessary because if you use field access, Hibernate does not distinguish getId() method from other ordinary methods (which trigger proxy initialization when invoked).

提交回复
热议问题