无法执行SQL语句
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法执行SQL语句相关的知识,希望对你有一定的参考价值。
在编写我的应用程序时,我遇到了执行SQL语句的问题。我试图在网上寻找解决方案,但没有找到帮助,我仍然不知道如何处理我得到的错误。这是我得到的例外:
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["FKAM8LLDERP40MVBBWCEQPU6L2S: PUBLIC.BOOK_CATEGORY FOREIGN KEY(CATEGORY_ID) REFERENCES PUBLIC.CATEGORY(ID) (2)"; SQL statement:
insert into book_category (book_id, category_id) values (?, ?) [23506-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
这就是类的外观:Book.class
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String title;
private String description;
@Column(name = "release_date")
@Temporal(TemporalType.TIMESTAMP)
private Date releaseDate;
@JoinColumn(name = "cover_image")
@OneToOne(cascade = CascadeType.MERGE)
private UploadFile coverImage;
@OneToOne(cascade = CascadeType.MERGE)
private UploadFile content;
@ManyToMany
@JoinTable(name = "book_category", joinColumns = {@JoinColumn(name = "book_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "category_id", referencedColumnName = "id")})
private Set<Category> categories;
// constructors, setters, getters
}
Category.class
@Entity
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "category_name")
private String name;
@ManyToMany(mappedBy = "categories", fetch = FetchType.LAZY)
private List<Book> books;
// ...
}
答案
你在那里缺少cascade
的定义。
您的图书类别在首先插入引用的实体(书籍或类别)之前编写。由于您指定的约束,因此不允许这样做。解决方案是定义
cascade = CascadeType.ALL
在连接的两侧(包括书籍和类别)。这将确保JPA以正确的顺序保留所有实体。
以上是关于无法执行SQL语句的主要内容,如果未能解决你的问题,请参考以下文章