Java Spring中POST请求@ManyToOne关系的JSON内容

tua*_*562 5 java spring hibernate jpa many-to-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
}
Run Code Online (Sandbox Code Playgroud)

许多类:

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
}
Run Code Online (Sandbox Code Playgroud)

仓库:

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

public interface ManyRepository extends JpaRepository<Many, Long> {
}
Run Code Online (Sandbox Code Playgroud)

控制器类别:

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了一条ID为1的记录。但是,当我使用JSON数据创建Many记录时:

{
    "name": "Foo",
    "one_id": 1
}
Run Code Online (Sandbox Code Playgroud)

我收到的one_id是多个记录null
可以仅使用一个请求来创建新的许多记录并分配给ID为1的一个记录吗?我是否必须使用2个请求:创建多个并分配给一个?

Abd*_*han 5

你必须像这样更新你的方法

@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
    
    
    ...

}
Run Code Online (Sandbox Code Playgroud)

注:以上答案仅解释了实体关系的设置方法。实际应该调用正确的服务层。