使用SpringBoot无法将ArrayList中的2个以上的元素保存到MySQL吗?

时间:2019-03-16 23:40:55

标签: java mysql sql spring-boot arraylist

我无法使用SpringBoot将ArrayList中的2个以上的元素保存到MySQL。当我对数组中的一个对象发出发布请求(Postman或Alamofire)时,我得到状态码200,否则我得到状态码500和springboot控制台中的此错误消息:

  

java.sql.SQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(quran-pro-coresurah,CONSTRAINT FKibuxjpjiwpq46220g7sn7y1q外键(id)参考文献reciterdocumentid

这些是我的课程:

@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

1 个答案:

答案 0 :(得分:0)

您的ManyToOne配置不正确,必须使用mappedBy元素来指定作为关系所有者的实体的关系字段或属性

  1. 第一个建议,使用双向关系:
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;
}
  1. 或使用单向关系:
 @OneToMany(cascade = CascadeType.ALL)
 private List<Surah> surahs;