开发者

JPA join fetch association table with N select generated by Hibernate?

I am using JPA with Hibernate3 as the implementation. I have an association table UsrGrp

Usr.java
@Id
@Basic(optional = false)
@Column(name = "usr_id")
private String usrId;
@OneToMany(ma开发者_运维问答ppedBy = "usr")
private List<UsrGrp> usrGrpList;

UsrGrp.java
@EmbeddedId
protected UsrGrpPK usrGrpPK;
@Column(name = "updated_by")
private String updatedBy;
@Column(name = "updated_date")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDate;
@JoinColumn(name = "grp_id", referencedColumnName = "grp_id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Grp grp;
@JoinColumn(name = "usr_id", referencedColumnName = "usr_id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Usr usr;

Grp.java
@Id
@Basic(optional = false)
@Column(name = "grp_id")
@OneToMany(mappedBy = "grp")
private List<UsrGrp> usrGrpList;

(Usr) 1--------* (UsrGrp) *--------1 (Grp)

When I execute the following sql.

SELECT DISTINCT usr FROM Usr usr LEFT JOIN FETCH usr.usrGrpList

Hibernate actually execute the same amount of select query as the numbers of Grp I have.

select grp0_.grp_id as grp1_6_0_ from grp grp0_ where grp0_.grp_id=?
select grp0_.grp_id as grp1_6_0_ from grp grp0_ where grp0_.grp_id=?
...

Is there anyway to avoid this N select queries? Thanks.


Yes. you can change the fetch mode from lazy to eager:

Criteria crit = session.createCriteria( Usr.class )
                           .setFetchMode( "usrgrp", FetchMode.JOIN )

where usrgrp is a set in Usr.class.


These queries are executed to load the grp of each fetched UsrGrp. Mark the ManyToOne from UsrGrp to Grp as lazy, and these queries should disappear. Or, if you want to load the groups in the same query, you could add a left join fetch to the query:

SELECT DISTINCT usr FROM Usr usr 
LEFT JOIN FETCH usr.usrGrpList userGroup 
LEFT JOIN FETCH userGroup.grp grp

You might also enable batch fetching to reduce the number of queries.

PS: Vowels are cool. UserGroup is much more readable than UsrGrp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜