2013-07-07 24 views
2

我有一個實體(MediaCostRule),有幾個常規字段並且一個關聯領域與@ElementCollection(MediaCostRuleSource)註釋使用Hibernate屬性投影獲取的關聯,並將它注入到DTO

我也有一個DTO(MediaCostRuleDto)保持該實體字段的子集,並且還包括在同一相關聯地設定

下面是類代碼

@Entity 
@Table(name = "media_cost_rules") 
public class MediaCostRule extends AdminEntity{ 

@Id 
@GeneratedValue 
@Column(name = "media_cost_rule_id") 
private Integer id; 

@Column(name = "name") 
@Length(max = 100) 
private String name; 

@Column(name="is_enabled") 
private Boolean enabled; 

@ManyToOne 
@JoinColumn(name = "brand_id") 
private Brand brand; 

@ElementCollection(fetch = FetchType.EAGER) 
@CollectionTable(name = "media_cost_rule_sources", joinColumns = @JoinColumn(name = "media_cost_rule_id")) 
private Set<MediaCostRuleSource> mediaCostRuleSources = new HashSet<MediaCostRuleSource>(); 

==================== =================================================

@Embeddable 
public class MediaCostRuleSource { 


@Column(name = "source_name") 
private String sourceName; 

@Column(name = "ordinal") 
private Integer ordinal; 

=========================================== =======================

public class MediaCostRuleDto extends AbstractAdminDto { 


@Size(min = 1) 
private Set<MediaCostRuleSource> mediaCostRuleSources = new HashSet<MediaCostRuleSource>(); 


@NotNull 
private String name; 

==================== ================================================== =====

現在我想要的是使用Projections來獲取mediaCostRuleSources和我的實體的名稱,並直接注入到我的MediaCostRuleDto(使用AliasToBeanResultTransformer)。

我曾嘗試下面的代碼:

@Test 
public void findByIdDirectTest2(){ 

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(MediaCostRule.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); 

    ProjectionList projectionList = Projections.projectionList(); 
    projectionList.add(Projections.property("name").as("name")); 
    projectionList.add(Projections.property("mediaCostRuleSources").as("mediaCostRuleSources")); 
    crit.setProjection(projectionList); 
    List list = crit.list(); 
} 

但我總是得到異常(ArrayIndexOutOfBoundsException異常)

必須有某種方式做這樣的事情與Hibernate

你知識 ??

Yosi

回答

0

你必須使用

crit.setFetchMode("mediaCostRuleSources",FetchMode.JOIN)