2

我有一个实体 (MediaCostRule),它有几个常规字段和一个用 @ElementCollection (MediaCostRuleSource) 注释的关联字段

我还有一个 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 做这样的事情

你知道如何 ??

约西

4

1 回答 1

0

你必须使用

crit.setFetchMode("mediaCostRuleSources",FetchMode.JOIN)
于 2013-08-05T15:07:22.720 回答