如何使用FetchType.Eager检索值?

时间:2013-08-08 00:03:55

标签: java hibernate java-ee jpa hibernate-mapping

我有三个班级,分别是国家,州和郊区。每个国家都有很多州,每个州都有许多郊区。

我的休眠是4.2.1.Final。

问题是虽然状态的FetchType定义为EAGER,但我无法检索每个州的郊区。

我也读过这个answer。因为我不想在检索国家的任何时候检索郊区的所有州。所以我认为需要使用标准而不是使用
来覆盖提取策略 @LazyCollection(LazyCollectionOption.FALSE)

国家

@Entity
public class Country {
 private List<States> states;
 ...
 public Country(){
  this.states = new ArrayList();
 }

 @OneToMany (cascade = CascadeType.ALL)
 public List<States> getStates() {
   return states;
 }
  ....
}

国家

@Entity
public class States {
  private long id;
  private String name;
  private List<Suburbs> suburbs;
  ...

  public States(){
   this.suburbs = new ArrayList();
  }

  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  public List<Suburbs> getSuburbs() {
    return suburbs;
  }
}

郊区

@Entity
public class Suburbs {
  private long id;
  private String name;
  ....
}

代码

Criteria criteria = session.createCriteria(Country.class, "country")
                        .createAlias("country.states", "states");
                ProjectionList pl = Projections.projectionList();
                pl.add(Projections.property("states.id").as("id"));
                pl.add(Projections.property("states.name").as("name"));
                criteria.setProjection(pl);

                criteria.setResultTransformer(new 
                             AliasToBeanResultTransformer(States.class));

                criteria.add(Restrictions.eq("country.id", id));

                List<States> statesList = new ArrayList();
                statesList = (List<States>) criteria.list();
                System.out.println(">>>" 
                            + statesList.get(0).getSuburbs().size()); 
                              >>>>> returns Zero

1 个答案:

答案 0 :(得分:0)

灵感来自thislink

User user = (User) session.createCriteria(User.class)
            .setFetchMode("permissions", FetchMode.JOIN)
            .add( Restrictions.idEq(userId) )
            .uniqueResult();