如何作为REST API的响应返回时将对象写入另一个对象?

时间:2016-12-21 20:22:38

标签: java rest api jpa httpresponse

我有两个课程address&使用customer方法的toString()。客户&地址是一对一映射。因此,每个客户都包含一个地址。让我们来看看以下......

  

我想要一个http响应: -

{
    "id": customerId,
    "addressId": addressId,
    "firstName": "first_name",
    "lastName": "last_name",
    "address": {
         "id": addressId,
         "street": "street",
         "city": "city",
         "country": "country",
         "postalCode": "postal_code"
    } 
}
  

Address.java

package com.maxpro.models;

import javax.persistence.*;


@Entity
public class Address {

    private Long id;
    private String street;
    private String city;
    private String country;
    private String postalCode;

    // getters & setters

    @Override
    public String toString () {
        return String.format("address[id='%d', street='%s', city='%s', country='%s', postalCode='%s']",
                                      id, street, city, country, postalCode
        );
    }

}
  

Customer.java

package com.maxpro.models;

import javax.persistence.*;


@Entity
public class Customer {

    private Long id;
    private Long addressId;
    private String firstName;
    private String lastName;

    private Address address;

    // getters & setters
    @Override
    public String toString() {
        return String.format(
                "customer[id=%d, addressId=%d, firstName='%s', lastName='%s', address='%s']",
                             id, addressId, firstName, lastName, address
        );
    }

}
  

CustomerRestController.java

package com.maxpro.controllers.rest;

import com.maxpro.models.Address;
import com.maxpro.models.Customer;
import com.maxpro.repositories.AddressRepository;
import com.maxpro.repositories.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/api/customers")
public class CustomerRestController {

    // CustomerRepository extends CrudRepository<Customer, Long>
    @Autowired
    private CustomerRepository customerRepository;

    // AddressRepository extends CrudRepository<Address, Long>
    @Autowired
    private AddressRepository addressRepository;

    @RequestMapping("/customer-with-address/{customerId}")
    public Customer getCustomerWithAddress(@PathVariable("customerId") Long customerId) {
        return customerRepository.findOne(customerId);
    }

}
  

它显示:

Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: 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: com.maxpro.models.Customer["address"]->com.maxpro.models.Address_$$_jvst556_1["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: com.maxpro.models.Customer["address"]->com.maxpro.models.Address_$$_jvst556_1["handler"])

如何获得预期结果?这意味着,如何在HTTP响应中将address对象放入customer

1 个答案:

答案 0 :(得分:1)

您需要急切地获取孩子即客户的地址。由于您使用的是JPA,因此两个实体之间应该存在关系。它可以是一对多或一对一......

确定要在两个实体之间维护的关系,并指定fetch类型。 例如:@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)