我在hibernate中建立一对多关系,但是当我试图插入一个值时
在表中,我的FK in photos实体不能为空。
我的父实体:

@Table(name = "library")
@Entity
public 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 null
com.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";}

    List<entity.photos> list = new ArrayList<>();
    for (MultipartFile photo : photos) {
        File file =null;
        if (!photo.isEmpty()) {
            try {
                validateImg(photo);
                file = new File(context.getRealPath("/uploadFile/" + photo.getOriginalFilename()));
                Logger.getAnonymousLogger().info("THE PATH IS " + file.getAbsolutePath());
                FileUtils.copyInputStreamToFile(photo.getInputStream(), file);
                file.createNewFile();
            } catch (IOException ex) {
                result.reject("uk_UA", "Поганий тип");
                return "addBook";
            }
        }
        if (file != null) {
            photos ph = new photos(photo.getOriginalFilename());
            StringBuilder builder = new StringBuilder();
            builder.append(file.getAbsolutePath());
            Logger.getAnonymousLogger().info("SOMETHING HAS BROKEN IN LOGGING FILE");
            System.out.println("INSIDE ADD METHOD ");
            list.add(ph);

        } else list.add(new photos(""));
    }
    book.getPhotosList().addAll(list);
    service.add(book);

    return "redirect:/books";
}

道:
   public void add(Book user) {
        currentSession().save(user);
}

最佳答案

最可能的情况是,您没有设置从照片到书本的反向引用,然后通过photoes集合将persist/merge操作从书本级联到书本。向集合中添加元素时,需要维护关系的两边。例如:

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.

09-08 02:39