【问题标题】:Using Hibernate property Projection to fetch association and inject it to Dto使用 Hibernate 属性 Projection 获取关联并将其注入 Dto
【发布时间】:2013-07-04 23:06:13
【问题描述】:

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

你知道吗??

约西

【问题讨论】:

    标签: hibernate associations projection many-to-one


    【解决方案1】:

    你必须使用

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

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 2018-04-05
      • 2016-08-04
      • 2011-10-03
      • 2018-09-12
      • 2020-09-14
      • 2013-10-04
      • 1970-01-01
      相关资源
      最近更新 更多