簡體   English   中英

Spring Data Rest投影不適用於單個資源

[英]Spring Data Rest projection does not work for single resources

我為實體類編寫了以下預測。

@Projection(name = "instituteProjection", types = { Institute.class })
public interface InstituteProjection {

    String getOrganizationName();

    Address getRegisteredAddress();
}

現在,每當我調用返回單個機構資源的URL http://localhost:8080/institutes/1?projection=instituteProjection ,我都嘗試應用此投影。 控制器GET方法的實現如下:

@RequestMapping(value = "institutes/{instituteId}", method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getInstitute(@PathVariable Long instituteId) {
    Institute institute = service.getInstitute(instituteId);
    return new ResponseEntity<>(institute, HttpStatus.OK);
}

問題是這還沒有退回學院的預測。 它返回默認的存儲庫json。

僅當我使用SDR生成的控制器而不是已實現的自定義rest控制器時,投影才起作用。

那么如何在自定義控制器中應用投影?

更新1學院班

@Data
@Entity
public class Institute{

 private String organizationName;

    @OneToOne
    private Address registeredAddress;

    @OneToOne
    private Address mailingAddress;

}

更新2

地址類別

    public class Address {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private long addressID;   

    @ManyToOne
    private Street street;

    @ManyToOne
    private Country country;

    private double latitude;

    private double longitude;

    @ManyToOne
    private City city;


}

非常簡單。 您可以使用現有的投影,甚至可以刪除@Projection注釋,這一點不是強制性的,以使其與自定義控制器一起使用。

因此,最小投影為:

public interface InstituteProjection {

    String getOrganizationName();

    Address getRegisteredAddress();

}

現在,要轉換您的Institute實體,您需要實現ProjectionFactory接口 ,現有的接口SpelAwareProxyProjectionFactory

為了使該類型的bean易於訪問,請添加一個小的配置:

@Configuration
public class ProjectionFactoryConfig {

    @Bean
    public ProjectionFactory projectionFactory() {
        return new SpelAwareProxyProjectionFactory();
    }

}

現在,您可以在Contoller中使用它來將您的研究所轉換為您的Instituteion:

@Autowired
private ProjectionFactory projectionFactory;

...

@RequestMapping(value = "institutes/{instituteId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getInstitute(@PathVariable Long instituteId) {
    final Institute institute = service.getInstitute(instituteId);
    final InstituteProjection instituteProjection = projectionFactory.createProjection(InstituteProjection.class, institute);
    return new ResponseEntity<>(instituteProjection, HttpStatus.OK);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM