即使标记为延迟加载,休眠的请求也会急切地

时间:2019-01-17 19:53:18

标签: hibernate lazy-loading

我具有以下实体关系。

  1. 一个用户有多个用户组。
  2. 每个UserGroup都有一个UserRole。

实体及其关系的映射方式如下:

public class UserGroup {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", referencedColumnName = "user_id", nullable = false)
    @Fetch(FetchMode.JOIN)
    private User user;

    @OneToOne(mappedBy = "userGroup", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @Setter(AccessLevel.NONE)
    @Fetch(FetchMode.JOIN)
    private UserRole userRole;

}
public class User {

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    @Fetch(FetchMode.JOIN)
    private Set<UserGroup> userGroups;
}
public class UserRole {

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_group_id")
    @Fetch(FetchMode.JOIN)
    private UserGroup userGroup;

}

当我执行类似以下内容的简单查询时:

userGroupDao.get(id)

我看到一个休眠查询,它连接了usergroup,user,userRole。我只需要userGroup查询,因为useruserRole都标记有FetchType.LAZY。这里有初始化问题吗?

这是休眠查询:

Hibernate: /* criteria query */ select ...<list of columns>... from user_groups this_ inner join users storeduser2_ on this_.user_id=storeduser2_.user_id left outer join user_roles storeduser3_ on this_.id=storeduser3_.user_group_Id where this_.id=?


Hibernate: select ...<list of columns>... user_groups usergroupn0_ left outer join user_roles storeduser1_ on usergroupn0_.id=storeduser1_.user_group_Id where usergroupn0_.user_id=?

1 个答案:

答案 0 :(得分:0)

根据link

  

在集合或单值关联上具有fetch =“ join”   映射,您实际上将避免执行第二个SELECT(因此,   关联或馆藏非延迟)