如何创建包含未映射到Entity字段的EntityView并添加自定义属性
EntityView添加非实体自定义属性实现方案
针对Blaze Persistence EntityView需要返回非Entity原生定义字段的需求,可通过以下3种常用方案实现:
- 方案1:使用
@Mapping注解配置JPQL子查询关联
如果DealRefDataBuyerView对应的DealRefData实体和DealListing存在可关联的字段(例如DealListing实体存在dealRefId字段关联到DealRefData主键),可以直接在抽象方法上添加@Mapping注解定义关联逻辑,框架会自动将子查询结果映射到对应的EntityView中:
@EntityView(DealListing.class) public abstract class DealListingBuyerView { abstract Long getId(); abstract Long getDealTypeId(); abstract DealRelatedType getDealRelatedType(); abstract String getRelatedCode(); abstract DealStatus getDealListingStatus(); abstract String getDealListingCompletionRate(); // 配置JPQL查询关联返回DealRefData,自动映射为DealRefDataBuyerView @Mapping("SELECT drd FROM DealRefData drd WHERE drd.id = dealRefId") abstract DealRefDataBuyerView getDealRefData(); }
该方案所有逻辑在一次查询中完成,性能最优,适合关联逻辑固定的场景。
- 方案2:使用
@MappingIgnore+@PostLoad回调自定义加载
如果关联逻辑比较复杂,需要调用业务层逻辑、或者需要执行多个独立查询才能获取属性值,可以用回调方法自行加载属性:
@EntityView(DealListing.class) public abstract class DealListingBuyerView { // 注入需要的业务Bean,Blaze Persistence支持Spring等主流依赖注入框架 @Inject transient DealRefDataRepository dealRefDataRepository; // 自定义存储属性 private DealRefDataBuyerView dealRefData; abstract Long getId(); abstract Long getDealTypeId(); abstract DealRelatedType getDealRelatedType(); abstract String getRelatedCode(); abstract DealStatus getDealListingStatus(); abstract String getDealListingCompletionRate(); // 告知框架无需从实体映射该字段 @MappingIgnore public DealRefDataBuyerView getDealRefData() { return dealRefData; } // 实体基础属性加载完成后执行自定义逻辑 @PostLoad public void loadCustomFields() { // 此处可编写任意自定义业务逻辑,包括多查询、动态计算等 this.dealRefData = dealRefDataRepository.findViewById(getDealTypeId()); } }
该方案灵活性最高,支持任意复杂的业务逻辑,适合需要多步查询、动态计算的场景,注意需要确保使用的Repository/Service已经被框架的依赖注入上下文托管。
- 方案3:简单计算属性直接写表达式
如果自定义属性是基于现有实体字段的简单计算结果,不需要额外查询,直接在@Mapping里写计算逻辑即可,示例如下:
// 示例:拼接两个字段返回自定义编码 @Mapping("CONCAT(relatedCode, '-', dealTypeId)") abstract String getCustomCombineCode();
内容的提问来源于stack exchange,提问作者Mayuran
相关产品推荐
相关产品推荐

