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

标签 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);
    }
}

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

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

但是如果我尝试通过POST将 JSON 保存到 .../add 来保存 Address:

{ "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不再暴露在界面上,而是做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没有嵌入,它们是 sibling 。通过为 AddressCityStateZip 提供存储库,您基本上将概念提升为聚合根,Spring Data REST 将其转换为专用的 HTTP 资源。在您的 HTTP 通信中,您现在将 CityStateZip 视为一个值对象,因为您不通过其标识符引用它 - 在 REST 上下文中 - 是您在 Location 中返回的 URI 第一个请求的 header 。

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

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

201 Created
Location: $createdZipUri

现在您可以使用返回的 URI 来创建地址:

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

201 Created
Location: $createdAddressUri

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

另一种选择是更改您的域类型/存储库结构,以不公开存储库或将 CityStateZip 转换为值对象。您遇到的错误是由于 Jackson 无法开箱即用地编码 Hibernate 代理造成的。确保你有 Jackson Hibernate module在类路径上。 Spring Data REST 将自动为您注册它。您可能想为 Address 中的 cityStateZip 属性切换到预先加载,因为它有效地消除了创建代理的需要,并且目标对象基本上是一组原语,所以为额外的加入付出的代价并不大。

关于java - 如何使用 Spring Data REST 存储库创建和连接相关资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27304504/

相关文章:

java - 无法启动嵌入式tomcat Spring boot

java - Android Studio : errors while running my program

java - 在示例 Java 项目中使用数据库的最简单方法?

php - 如何使用 PHP PDO 准备语句在 mysql 中插入大量相似的数据

php - 从字符串生成数组

spring - 如何在 Web 上下文初始化时调用 spring bean 中的方法

java - 如何将spring配置与webflow配置连接起来?

java - 如何在使用 proguard-maven-plugin 后组装项目

java - Selenium 2 窗口切换 : Java

python - Stripe : How to convert stripe model object into JSON to get complete hierarchical data?