gpt4 book ai didi

Java Spring - 仅保存(POST)来自 ManyToOne 关系的 id

转载 作者:行者123 更新时间:2023-12-05 06:36:32 27 4
gpt4 key购买 nike

我目前有两个实体:Call 和 CallSource。我在 Call 和 CallSource 之间存在 ManyToOne 关系。我想要的是当我进行 JSON POST 时仅使用 CallSource 的 ID 而不是整个对象并自动为调用生成 CallSource 对象。

调用.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上只有一个字段。

最佳答案

这样就可以了

{
"name": "John Doe",
"email": "johdoe@example.com",
"phone": "0000000000",
"budget": 99999,
"source": {"id":1}
}

关于Java Spring - 仅保存(POST)来自 ManyToOne 关系的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019239/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com