我无法使用SpringBoot将ArrayList中的2个以上的元素保存到MySQL。当我对数组中的一个对象发出发布请求(Postman或Alamofire)时,我得到状态码200,否则我得到状态码500和springboot控制台中的此错误消息:
java.sql.SQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(
quran-pro-core
。surah
,CONSTRAINTFKibuxjpjiwpq46220g7sn7y1q
外键(id
)参考文献reciter
(documentid
)
这些是我的课程:
@RestController
public class ReciterController {
@Autowired
private ReciterService reciterService;
@PostMapping("/reciters")
public String saveReciter(@RequestBody Reciter reciter) {
reciterService.saveReciter(reciter);
return "SUCCESS";
}
}
@Service
public class ReciterService {
@Autowired
private ReciterRepostitory reciterRepository;
public void saveReciter(Reciter reciter) {
reciterRepository.save(reciter);
}
}
@Entity
public class Reciter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long documentID;
@Column
private String name;
@Column
private String image;
@OneToMany(mappedBy="id", cascade = CascadeType.ALL)
private List<Surah> surahs;
// Constructor and getters and setters
}
@Entity
public class Surah {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private int number;
// Constructor and getters and setters
}
此主体有效:
{
"name": "reciter1",
"image": "/reciter1/image.png",
"surahs": [
{
"name": "LOLll",
"number": 0
}
]
}
这不是:
{
"name": "reciter1",
"image": "/reciter1/image.png",
"surahs": [
{
"name": "LOLll",
"number": 0
},
{
"name": "test2",
"number": 1
}
]
}
enter code here
答案 0 :(得分:0)
您的ManyToOne
配置不正确,必须使用mappedBy
元素来指定作为关系所有者的实体的关系字段或属性
public class Reciter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long documentID;
@Column
private String name;
@Column
private String image;
@OneToMany(mappedBy="reciter", cascade = CascadeType.ALL)
private List<Surah> surahs;
// Constructor and getters and setters
}
@Entity
public class Surah {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private int number;
@ManyToOne
private Reciter reciter;
}
@OneToMany(cascade = CascadeType.ALL)
private List<Surah> surahs;