【发布时间】:2019-08-04 11:37:16
【问题描述】:
我想使用 RequestBody 接收从前端发布的数据库对象并将其转换为 Java 对象。这个数据库对象包含外键。
课程表结构:
create table course
(
id bigint auto_increment
primary key,
code varchar(255) null,
name varchar(255) null,
department_id int null
)
engine=MyISAM;
create index FK8m89mn0y32bm9vko2bcfkag53
on course (department_id);
department_id 是 FK 参考部门表。
这是我的课程实体:
package com.elfstack.aims.api.entity;
import lombok.Data;
import javax.persistence.*;
import java.util.Set;
@Data
@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String code;
private String name;
@ManyToOne
private Department department;
}
当我想创建一个新的课程记录时,我从前端发送一个 JSON 对象:
{"code":"123","name":"123","department_id":123}
而我使用这个方法来处理这个请求:
@PostMapping("/courses")
public JSON createCourse(@RequestBody Course course) {...}
当然,我无法通过这种方式获取department_id,但我也认为当我想创建新课程记录时,从前端发送entier Department对象不是一个好主意,那么什么是最好的方法?
【问题讨论】:
标签: spring-boot spring-data-jpa