Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON content for POST request @ManyToOne relationship in Java Spring

I have two models:
Class One:

import javax.persistence.*;
import java.util.Set;

@Entity
public class One {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @OneToMany(mappedBy = "one")
    private Set<Many> manySet;

    //Constructor, Getter and Setter
}

Class Many:

import javax.persistence.*;

@Entity
public class Many {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name = "one_id")
    private One one;
    //Constructor, Getter and Setter
}

Repository:

import com.hotel.model.Many;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ManyRepository extends JpaRepository<Many, Long> {
}

Controller Class:

@RestController
@RequestMapping(value = "many")
public class ManyController {
    @Autowired
    private ManyRepository manyRepository;

    @GetMapping
    @ResponseBody
    public List<Many> getAllMany() {
        return manyRepository.findAll();
    }

    @PostMapping
    @ResponseBody
    public ResponseEntity createMany(@RequestBody Many many) {
        return new ResponseEntity(manyRepository.save(many), HttpStatus.CREATED);
    }
}

I created One record with id=1. But when I create a Many record with JSON data:

{
    "name": "Foo",
    "one_id": 1
}

I received Many record with one_id is null
Can I using only one request to create new Many record and assign to One record has id = 1? Do I have to use 2 request: create Many and assign to One?

like image 261
tuannv.256 Avatar asked Oct 22 '17 05:10

tuannv.256


1 Answers

You have to update your method like so

@PostMapping
@ResponseBody
public ResponseEntity createMany(@RequestBody ManyDTO many) {
    
    One one = oneRepository(many.getOne_id()); //Get the parent Object
    
    Many newMany  = new Many(); //Create a new Many object
    newMany.setName(many.getName());
    newMany.setOne(one); // Set the parent relationship
    
    
    ...

}

Note: The above answer only explains the way to set the relationships of the entity. Proper service layer should be invoked actually.

like image 85
Abdullah Khan Avatar answered Oct 24 '22 02:10

Abdullah Khan