Java Spring - 仅从ManyToOne关系

时间:2018-02-27 22:51:23

标签: java spring jpa spring-boot

我目前有两个实体:Call和CallSource。我在Call和CallSource之间有一个ManyToOne关系。我想要的是当我进行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
}

使这成为可能的最佳方法是什么?不使源成为对象,只有json上的字段。

1 个答案:

答案 0 :(得分:0)

这样做

x=5
magicSave(x,file="saved_variable_1.r",to_save_as="result_1")
x=93
magicSave(x,file="saved_variable_2.r",to_save_as="result_2")
load(saved_variable_1)
load(saved_variable_2)
result_1
#returns 5
result_2
#returns 93