我有一个使用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将此JSON转换为POST来保存http://example.com:8080/zip:
{ "zipCode" : "28899" , "city" : "Ada", "stateProv" : "NC" }

但是如果我尝试通过将JSON转换为AddressPOST来保存…/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,则可以将AddressCSZ保存到数据库中。但是在那时,…/zip不再在接口(interface)上公开,并且执行GET …/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"
}

是否有一种方法可以设置此模型以能够从该数据库中生成POSTGET?另外,传递给Address的JSON将保存一个新的CityStateZip实例-哪种格式将允许我们引用现有的CityStateZip元素?

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

最佳答案

在如何使用对象以及如何在域对象/存储库结构中设置对象方面存在不匹配。这是您有效执行的操作:

与您在问题的原始标题(“在RestRepository中获取和发布嵌套的实体”)中询问的相反,在HTTP级别上,AddressCityZipState未嵌入,它们是同级的。通过提供AddressCityStateZip的存储库,您基本上可以提升概念以聚合根,Spring Data REST将其转换为专用的HTTP资源。现在,在HTTP通信中,您将CityStateZip视为值对象,因为您没有通过其标识符来引用它,该标识符在REST上下文中是您在第一个请求的Location header 中返回的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

因此,您基本上要表达的是:“请创建一个包含这些详细信息的地址,但请引用此CityZipState。”

另一种选择是更改您的域类型/存储库结构,以不公开存储库或将CityStateZip转换为值对象。您遇到的错误是由于Jackson无法开箱即用地整理Hibernate代理引起的。确保类路径上有Jackson Hibernate module。然后,Spring Data REST会自动为您注册。您可能想要切换到急切地加载cityStateZip中的Address属性,因为它实际上消除了创建代理的需要,并且目标对象基本上是一组基元,因此为附加的连接付出的代价并不大。

07-27 22:14