Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring - Save (POST) only id from ManyToOne relationship

I currently have two entities: Call and CallSource. I have a ManyToOne relatioship between Call and CallSource. What I want is when I make a JSON POST use only the id of the CallSource and not the whole object and automatically generate the CallSource object for the Call.

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
}

Call Source

@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>
{
}

I want to make a JSON POST like that:

{
      "name": "John Doe",
      "email": "[email protected]",
      "phone": "0000000000",
      "budget": 99999,
      "source": 1
}

What is the best way to make that possible? Without making source an object, only a field on the json.

like image 287
Someone Lost Avatar asked May 16 '26 19:05

Someone Lost


1 Answers

This will do

{
      "name": "John Doe",
      "email": "[email protected]",
      "phone": "0000000000",
      "budget": 99999,
      "source": {"id":1}
}
like image 185
Antoniossss Avatar answered May 19 '26 10:05

Antoniossss