Hibernate Issuing select statement even if FetchMode = Join
I have a userAccount entity mapped with a country entity . The country mapping in UserAccount class is like this
@ManyToOne(fetch=FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JoinColumn(name="f_country_id", nullable=true, insertable=false, updatable=开发者_如何学Gofalse)
private Country country;
Even there is fetchmode defined as Join, hibernate fires a separate SQL Select to fetch countries.
Remove the fetch=FetchType.EAGER
. Eager fetching triggers cascading select statements.
If you are using explicit HQL query e.g. "from User where something = someValue", Hibernate will not respect the annotated Fetch mode. You would need to specify the join in the HQL query or the fetch mode in the criteria.
Satadru Biswas gave the answer in a previous comment .
Hibernate 3.x ignores the FetchMode annotation when you use the Query interface (Session.createQuery) so in this case you have to add an INNER JOIN FETCH clause to the FROM part of your query.
The criteria interface however will use this interface correctly.
I try use @Fetch(FetchMode.JOIN) hibernate adnotation in all api (JPQL and CriteriaBuilder) but didn't work. Only this code in service class work fine:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<UserAccount > cq = cb.createQuery(UserAccount.class);
Root<UserAccount> o = cq.from(UserAccount.class);
o.fetch("country",JoinType.INNER);
em.createQuery(cq.select(o)).getResultList();
I'm using the criteria query to fetch Customers.
public class PurchaseOrder
{
.....
.....
@ManyToOne(fetch=FetchType.EAGER, optional=true)
@JoinColumn(name="ReportingCustomer_ID", nullable=true, insertable=false, updatable=false)
@Fetch(FetchMode.JOIN)
@NotFound(action=NotFoundAction.IGNORE)
public ReportingCustomer getReportingCustomer()
{
return reportingCustomer;
}
}
While getting PurchaseOrder it does a LEFT OUTER JOIN as below
select ... from PurchaseOrder this_ left outer join ReportingCustomer reportingc2_
on this_.ReportingCustomer_ID=reportingc2_.ReportingCustomer_ID
where ...
- When there is an entry in ReportingCustomer - It fires only the above query.
- When there is no entry for that record in ReportingCustomer - It fires a query for each PURCHASEORDER (m+1) queries.
I use "Progress" driver to connect to DB. I'm not sure why it fires m+1 queries only in scenario 2.
精彩评论