【问题标题】:Exposing both parent and child entities as REST repositories in Spring Data REST在 Spring Data REST 中将父实体和子实体公开为 REST 存储库
【发布时间】:2018-05-25 16:52:42
【问题描述】:

我在 Spring Date REST 存储库中配置了一个父子实体。父级是这样的

@Entity
@Table(name = "DPST_DTL")
public class Deposit {

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "deposit", orphanRemoval=true)
    private List<Instrument> instrumentList = new ArrayList<Instrument>();
}

孩子长这样:

@Entity
@Table(name = "INSTR_DTL")
public class Instrument {

    @ManyToOne
    @JoinColumn(name = "DPST_ID")
    @JsonBackReference
    private Deposit deposit;
}

我已经为 Deposit 定义了一个 RepositoryRestresource 如下:

@RepositoryRestResource(collectionResourceRel = "deposit", path = "deposit")
public interface DepositRepository extends PagingAndSortingRepository<Deposit, Long>{

}

与 Instrument 相同,如下:

@RepositoryRestResource(collectionResourceRel = "instrument", path = "instrument")
public interface InstrumentRepository extends PagingAndSortingRepository<Instrument, Long>{

}

如果我尝试用一​​些子记录发布父级,我会收到如下消息: “消息”:“无法将类型 [java.net.URI] 转换为类型 [com.XXX.irh.insprc.instrument.Instrument] 的值 'countryCode';嵌套异常是 java.lang.IllegalArgumentException:无法解析 URI countryCode。它是本地的还是远程的?只有本地 URI 是可解析的。 },

“countryCode”恰好是子 JSON 中的第一个字段

如果我查询带有一些子项的父项,则生成的 JSON 不会扩展子项,而只会显示如下链接: "instrumentList": {"href": "http://localhost:9090/deposit/8/instrumentList"}

但是,如果我用exported=false 标记子存储库,我就能解决这个问题。但是子实体不能通过 REST API 公开。

问题是:

我是否可以为父实体和子实体公开基本的 CRUD 功能,而无需编写自定义控制器等?

我了解,根据 DDD 最佳实践,我的父级是一个应该通过 REST 存储库公开的聚合体,但不幸的是,我确实有一些用例需要为两者提供独立的 CRUD 功能。

【问题讨论】:

    标签: spring-data-rest


    【解决方案1】:

    你可以使用projections:

    @Projection(name = "withInstruments", types = Person.class)
    public interface WithInstruments {
    
       @Value("#{target.depositName}")
       String getDepositName();
    
       List<Instrument> getInstrumentList();  
    }
    

    然后您可以将您的实体组合在一起:

    GET /deposits?projection=withInstruments
    {
       "depositName": "deposit1",
       "instrumentList": [
           {
               "intrumentName": "instrument1",
           },
           {
               "intrumentName": "instrument1",
           }
       ]
    }
    

    补充info

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-21
      • 2017-12-02
      • 2019-09-30
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      • 2012-10-04
      相关资源
      最近更新 更多