我在休眠中建立了一对多的关系,但是当我尝试在表中插入一个值时,我得到了我的照片实体中的 FK 不能为空的异常。我的父实体:@Table(name = "library")@Entitypublic class Book {@OneToMany( fetch = FetchType.LAZY, mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)// setters / getters and other columns 我的子实体@Entity@Table(name = "photos")public class photos{@Id@GeneratedValue(strategy = GenerationType.AUTO)@Column(name = "idphotos")private int id;@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)@JoinColumn(name = "library_idlibrary")private Book book;// other columns 例外:java.sql.SQLIntegrityConstraintViolationException: Column 'library_idlibrary' cannot be nullcom.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:115)com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)我有插入值的 DAO 对象和控制器:控制器: @PostMapping( value = "/newBook",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})public String add(@ModelAttribute("book") @Valid Book book, HttpServletResponse response, HttpServletRequest request,@RequestParam(value = "photo", required = false) List<MultipartFile> photos, @RequestParam(value = "valute",required = false) String valute,BindingResult result) { if (result.hasErrors()) { return "addBook";}
1 回答
忽然笑
TA贡献1806条经验 获得超5个赞
很可能您还没有设置从 Photo 到 Book 的反向引用,然后您通过 photoes 集合从 Book 级联持久/合并操作。当您将元素添加到集合时,您需要维护关系的双方。例如:
Book book = new Book();
Photo photo = new Photo();
book.addPhoto(photo);
photo.setBook(book);
//notice on the line above we set the backreference of the photo to the book.
hibernateSession.persist(book);
// now it is cascading from book to photo and it will set the foreign keys correctly.
添加回答
举报
0/150
提交
取消