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

标签 java rest api jpa httpresponse

我有两个带有 toString() 方法的类 addresscustomer 。客户和地址是一对一映射的。因此,每个客户都包含一个地址。让我们看看下面...

I would like to have a http response as:-

{
    "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);
    }

}

It shows:

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"])

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

最佳答案

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

决定您想要在两个实体之间维护的关系,然后指定获取类型。 例如:@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)

关于java - 如何将一个对象写入另一个对象,同时作为 REST API 的响应返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41271291/

相关文章:

javascript - 从 API 获取和输出数据的问题

java - 我们如何在测试 Web 应用程序时打开多个 IE 实例。在 eclipse 中使用 selenium RC 和 java?

java - @Produces 和@Consumes 的 Jersey (dropwizard)默认媒体类型

c# - C# (MVC-5) 中 GetResponse API 版本 3 的 header

java - 使用 REST 发送文件?

c# - ASP.NET 无法解析 xml!检查文件路径

javascript - 是否缓存:true in ajax request is enough for saving bandwidth?

java - 在 Eclipse ( OSX ) 中导入 Apache 数学类

java - 字符串到数组字符串的精确副本! DPLL算法

java - 如何获取特定日志文件并在 jenkins 控制台输出中显示其内容