【发布时间】:2018-02-27 22:51:22
【问题描述】:
我目前有两个实体:Call 和 CallSource。我在 Call 和 CallSource 之间存在多对一关系。我想要的是,当我进行 JSON POST 时,只使用 CallSource 的 id 而不是整个对象,并自动为 Call 生成 CallSource 对象。
Call.java
@Entity
public class Call
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String email;
private String phone;
private Date date;
@ManyToOne
@JoinColumn(name = "source_id")
private CallSource source;
// Constructors, getters and setters
}
来电来源
@Entity
public class CallSource
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(length = 100)
private String name;
// Constructors, getters and setters
}
CallController.java
@RestController
@RequestMapping("api/")
public class CallController
{
@Autowired
private CallService callService;
@RequestMapping(value = "call", method = RequestMethod.POST)
public Call create(@RequestBody Call call)
{
return callService.create(call);
}
}
CallService.java
@Service
public class CallService
{
@Autowired
private CallRepository callRepository;
public Call create(Call call)
{
return callRepository.saveAndFlush(call);
}
}
CallRepository.java
@Repository
public interface CallRepository extends JpaRepository<Call, Long>
{
}
我想做一个这样的 JSON POST:
{
"name": "John Doe",
"email": "johdoe@example.com",
"phone": "0000000000",
"budget": 99999,
"source": 1
}
实现这一目标的最佳方法是什么?不将 source 设为对象,仅在 json 中添加一个字段。
【问题讨论】:
标签: java spring jpa spring-boot