0

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

我的休眠是 4.2.1.Final。

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

我也读了这个答案。因为我不想在检索国家/地区时检索所有州和郊区。所以我想需要使用标准而不是使用
@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
4

1 回答 1

0

受此启发链接

User user = (User) session.createCriteria(User.class)
            .setFetchMode("permissions", FetchMode.JOIN)
            .add( Restrictions.idEq(userId) )
            .uniqueResult();
于 2013-08-08T01:10:43.947 回答