如何使用Spring Data REST存储库创建和连接相关资源?

时间:2014-12-04 21:32:15

标签: java json spring rest spring-data-rest

我使用Spring Data REST / RestRepository架构进行了简单的概念验证演示。我的两个实体是:

@Entity
@org.hibernate.annotations.Proxy(lazy=false)
@Table(name="Address")
public class Address implements Serializable {

    public Address() {}

    @Column(name="ID", nullable=false, unique=true) 
    @Id 
    @GeneratedValue(generator="CUSTOMER_ADDRESSES_ADDRESS_ID_GENERATOR")    
    @org.hibernate.annotations.GenericGenerator(name="CUSTOMER_ADDRESSES_ADDRESS_ID_GENERATOR", strategy="native")  
    private int ID;

    @RestResource(exported = false)
    @ManyToOne(targetEntity=domain.location.CityStateZip.class, fetch=FetchType.LAZY)   
    @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.PERSIST}) 
    @JoinColumns({ @JoinColumn(name="CityStateZipID", referencedColumnName="ID", nullable=false) }) 
    private domain.location.CityStateZip cityStateZip;

    @Column(name="StreetNo", nullable=true) 
    private int streetNo;

    @Column(name="StreetName", nullable=false, length=40)   
    private String streetName;

    <setters and getters ommitted>  
}

CityStateZip

@Entity
public class CityStateZip {

    public CityStateZip() {}

    @Column(name="ID", nullable=false, unique=true) 
    @Id 
    @GeneratedValue(generator="CUSTOMER_ADDRESSES_CITYSTATEZIP_ID_GENERATOR")   
    @org.hibernate.annotations.GenericGenerator(name="CUSTOMER_ADDRESSES_CITYSTATEZIP_ID_GENERATOR", strategy="native") 
    private int ID;

    @Column(name="ZipCode", nullable=false, length=10)  
    private String zipCode;

    @Column(name="City", nullable=false, length=24) 
    private String city;

    @Column(name="StateProv", nullable=false, length=2) 
    private String stateProv;

}

使用存储库:

@RepositoryRestResource(collectionResourceRel = "addr", path = "addr") 
public interface AddressRepository extends JpaRepository<Address, Integer> {

     List<Address> findByStreetNoAndStreetNameStartingWithIgnoreCase(@Param("stNumber") Integer streetNo, @Param("street") String streetName);
     List<Address> findByStreetNameStartingWithIgnoreCase(@Param("street") String streetName);
     List<Address> findByStreetNo(@Param("streetNo") Integer strNo);
}

// @RepositoryRestResource(collectionResourceRel = "zip", path = "zip", exported = false)
@RepositoryRestResource(collectionResourceRel = "zip", path = "zip")
public interface CityStateZipRepository extends JpaRepository<CityStateZip, Integer> {

    List<CityStateZip> findByZipCode(@Param("zipCode") String zipCode);
    List<CityStateZip> findByStateProv(@Param("stateProv") String stateProv);
    List<CityStateZip> findByCityAndStateProv(@Param("city") String city, @Param("state") String state);
}

的main()代码
@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
// @EnableTransactionManagement
@PropertySource(value = { "file:/etc/domain.location/application.properties" })
@ComponentScan
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

使用此代码,我可以CSZ POST将此JSON保存到http://example.com:8080/zip

{ "zipCode" : "28899" , "city" : "Ada", "stateProv" : "NC" }

但如果我尝试将Address POST {J} …/add { "streetNo" : "985" , "streetName" : "Bellingham", "plus4Zip" : 2212, "cityStateZip" : { "zipCode" : "28115" , "city" : "Mooresville", "stateProv" : "NC" } } 保存到{ "cause": { "cause": { "cause": null, "message": "Template must not be null or empty!" }, "message": "Template must not be null or empty! (through reference chain: domain.location.Address[\"cityStateZip\"])" }, "message": "Could not read JSON: Template must not be null or empty! (through reference chain: domain.location.Address[\"cityStateZip\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Template must not be null or empty! (through reference chain: domain.location.Address[\"cityStateZip\"])" }

CityStateZipRepository

我收到错误

export=false

现在,如果我在注释中更改Address以包含CSZ,我就可以将…/zipGET保存到数据库中。但那时,…/addr不再在界面上公开,而…/addr/{id} { "timestamp": 1417728145384, "status": 500, "error": "Internal Server Error", "exception": "org.springframework.http.converter.HttpMessageNotWritableException", "message": "Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.hateoas.PagedResources[\"_embedded\"]->java.util.UnmodifiableMap[\"addr\"]->java.util.ArrayList[0]->org.springframework.hateoas.Resource[\"content\"]->domain.location.Address[\"cityStateZip\"]->domain.location.CityStateZip_$$_jvst4e0_0[\"handler\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.springframework.hateoas.PagedResources[\"_embedded\"]->java.util.UnmodifiableMap[\"addr\"]->java.util.ArrayList[0]->org.springframework.hateoas.Resource[\"content\"]->domain.location.Address[\"cityStateZip\"]->domain.location.CityStateZip_$$_jvst4e0_0[\"handler\"])", "path": "/addr" } POST会导致此错误:

GET

有没有办法将此模型设置为能够从此数据库中AddressCityStateZip?此外,传递给CityStateZip的JSON将保存{{1}}的新实例 - 允许我们引用现有{{1}}元素的格式是什么?

感谢您提供的任何帮助 - 这让我们疯狂了几天。

2 个答案:

答案 0 :(得分:3)

您使用对象的方式与您在域对象/存储库结构中的设置方式不匹配。这是你有效的做法:

与您在问题的原始标题中提到的内容(&#34;在RestRepository和#34中获取和发布嵌套实体;)相比,在HTTP级别上,AddressCityZipState是没有嵌入,他们是兄弟姐妹。通过为AddressCityStateZip提供存储库,您基本上将概念提升为聚合根,Spring Data REST将其转换为专用HTTP资源。在您的HTTP通信中,您现在将CityStateZip视为值对象,因为您不会通过其标识引用它 - 在REST上下文中 - 是您在Location中返回的URI第一个请求的标题。

因此,如果您希望保持域类型/存储库结构不变,则需要按如下方式更改HTTP交互:

POST $zipsUri { "zipCode" : "28899" , "city" : "Ada", "stateProv" : "NC" }

201 Created
Location: $createdZipUri

现在您可以使用返回的URI创建Address

POST $addressesUri { "streetNo" : "985" ,  "streetName" : "Bellingham",   "plus4Zip" : 2212,  "cityStateZip" : $createdZipUri }

201 Created
Location: $createdAddressUri

所以你基本上表达的是:&#34;请创建一个包含这些细节的地址,但请参阅这个CityZipState。&#34;

另一种选择是将域类型/存储库结构更改为不公开存储库或将CityStateZip转换为值对象。您遇到的错误是由杰克逊无法开箱即用编组Hibernate代理引起的。确保类路径上有Jackson Hibernate module。 Spring Data REST会自动为您注册。您可能希望切换到cityStateZipAddress属性的急切加载,因为它有效地删除了创建代理的需要,并且目标对象基本上是一组基元,因此它们就是这样的。为额外的加入付出的代价并不高。

答案 1 :(得分:2)

假设父实体已经存在(在本例中为CityStateZip),请通过引用CityStateZip的URI来创建地址:

{ "streetNo" : "985" ,  "streetName" : "Bellingham",   "plus4Zip" : 2212,  "cityStateZip" : "http://example.com:8080/zip/idOfZip"    }