模型映射的Spring JPA JSON没有映射到右列

时间:2017-08-09 06:05:00

标签: java spring postgresql jpa

所以我跟随this tutorial学习Spring,JPA作为REST API并执行CRUD操作。我在PostgreSQL中使用以下模式定义了一个表:

firstname

当我尝试使用以下代码创建新客户时,会创建客户,但不会将lastnamefirst_name数据插入相应字段,而是将数据插入新列名为last_name// all imports @RestController public class BaseController { @Autowired CustomerRepository repository; @RequestMapping(value = "/postcustomer", method = RequestMethod.POST) public void postCustomer(@RequestBody Response request) { request.getData().forEach((data) -> { repository.save(data.getCustomer()); }); } } 。这种映射是如何进行的?

控制器 - BaseController.java:

// all imports
public class Response implements Serializable {
    private String status;
    private List<Data> data;
    public Response(String status, List<Data> data) {
        this.status = status;
        this.data = data;
    }
    public Response() {
    }
    //all getter setters below
}

JSONMapping - Response.java:

// all imports
public class Data implements Serializable{
    @JsonProperty("Customer")
    private Customer customer;
    public Data() {
    }
    public Data(Customer customer) {
        this.customer = customer;
    }
    // all getter setters
}

JSON映射 - Data.java:

// all imports
@Entity
@Table(name = "customer")
public class Customer implements Serializable {
    private static final long serialVersionUID = -3009157732242241606L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @JsonProperty("firstname")
    @Column(name = "firstname")
    private String firstName;
    @JsonProperty("lastname")
    @Column(name = "lastname")
    private String lastName;
    protected Customer() {
    }
    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    // all getter setters
}

模型 - Customer.java:

// all imports
public interface CustomerRepository extends CrudRepository<Customer, Long> {

}

存储库 - CustomerRepository.java:

{
    "status": "Done",
    "data": [ {
        "Customer": {
            "firstname" : "test",
            "lastname" : "123"
        }
    }]
}

正在发送JSON:

*

1 个答案:

答案 0 :(得分:2)

这是因为Spring JPA使用自己的默认命名约定。 只需将以下行放在application.properties文件

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl