Hibernate generating SQL queries when accessing associated entity's id

前端 未结 3 483
我寻月下人不归
我寻月下人不归 2020-12-09 06:26

I have Hibernate Entities that look something like this (getters and setters left out):

@Entity
public class EntityA {
    @ManyToOne(fetch = FetchType.LAZY)         


        
相关标签:
3条回答
  • 2020-12-09 06:56

    What you say makes sense - that it would not make a DB hit since EntityA contains the parent ID. I am just not sure if the getParent() call actually loads the EntityB object regardless of whether all you're interested in is the ID. You might try marking the children collection (and any other fields) as Lazy if you want to save the DB hit.

    @Entity
    public class EntityB : SuperEntity {
        @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
        @Fetch(FetchMode.SUBSELECT)
        @JoinColumn(name = "parent_id")
        private Set<EntityA> children;
    }
    
    0 讨论(0)
  • 2020-12-09 07:04

    As I understand that call should NOT make a roundtrip to the database, as the Id is stored in the EntityA table, and the proxy should only return that value.

    Use property access type. The behavior you're experiencing is a "limitation" of field access type. Here is how Emmanuel Bernard explained it:

    That is unfortunate but expected. That's one of the limitations of field level access. Basically we have no way to know that getId() indeed only go and access the id field. So we need to load the entire object to be safe.

    So change your code into:

    @Entity
    public class EntityA {
        private EntityB parent;
    
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "parent_id")
        public EntityB getParent() {
            return parent; 
        }
        ...
    }
    
    @MappedSuperclass
    public class SuperEntity {
        private long itemId;
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "id")
        public long getItemId() { 
            return itemId;
        }
        ...
    }
    

    Related question

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

    References

    • Proxy loaded on getId-call when using annotations on fields
    • proxy getId => why sql is generated !
    • HHH-3718 (if this issue can ever be solved)
    0 讨论(0)
  • 2020-12-09 07:08

    As for Hibernate:
    This behavior has been changed since Hibernate 5.2.12.

    0 讨论(0)
提交回复
热议问题