【问题标题】:Java Spring - Save (POST) only id from ManyToOne relationshipJava Spring - 仅保存(POST)来自ManyToOne关系的ID
【发布时间】: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


    【解决方案1】:

    这样就可以了

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

    【讨论】:

    • 还有其他方法吗?没有将“源”作为对象,只有 json 上的一个字段?
    • 这里有什么区别?我刚刚添加了 2 个括号和“id”。
    • @Antoniossss 如果源模型中的任何其他文件标记为非空怎么办?您最终将在额外的 2 个括号内再添加一个键值。
    • 没关系,因为这不会创建新源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2021-08-17
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多