[英]Unique constraint on combination of more than two columns
我有两个表的书 ,我试图建立一个双向一到他们之间有很多关系页面 。
页面对无法正常工作的多个列具有唯一的约束。 当我插入具有唯一page_item的book_item时,它按预期的方式工作,但是当我尝试删除也应该删除页面的书时,我得到了唯一的约束违例异常 ,我不太了解。 我正在使用jpa存储库执行插入/删除操作。
当我删除@UniqueConstraint时,删除仍然有效,但约束不起作用,所以我不太了解自己在做什么错。
@Entity
@Table(name = "book")
@NoArgsConstructor
@RequiredArgsConstructor
public class Book implements Serializable {
@Id
@GeneratedValue(generator = "book_uuid")
@GenericGenerator(name = "book_uuid", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", updatable = false, nullable = false, columnDefinition = "VARCHAR(255)")
@Type(type="uuid-char")
@Getter
private UUID id;
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
@Getter
@Setter
private List<Page> pages;
}
@Entity
@Table(name = "page", uniqueConstraints = @UniqueConstraint(columnNames = {"book_id", "chapter", "volume", "name"}))
@NoArgsConstructor
@RequiredArgsConstructor
public class Page implements Serializable {
@Id
@GeneratedValue(generator = "page_uuid")
@GenericGenerator(name = "page_uuid", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", updatable = false, nullable = false, columnDefinition = "VARCHAR(255)")
@Type(type="uuid-char")
@Getter
private UUID id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "book_id", nullable = false)
@Getter
@Setter
@NonNull
private Book book;
@Column(name = "chapter", nullable = false)
@Getter
@Setter
private int chapter = 0;
@Column(name = "volume", nullable = false)
@Getter
@Setter
private int volume = 0;
@Column(name = "name", nullable = false)
@Getter
@Setter
@NonNull
private String name;
}
// Code used for insertion/update /deletion
@Repository
public interface BookRepository extends JpaRepository<Book, UUID> {
}
public void test() {
Book book = bookRepository.findById("9c7b2ab2-1c78-4e9f-adc5-99c7da42a7c6");
List<Page> pages = IntStream.range(0, 5)
.mapToObj(i -> new Page(book, "Page" + i, ".png"))
.collect(Collectors.toList());
book.setPages(pages);
bookRepository.save(book);
bookRepository.delete(book);
我得到的错误信息:
org.springframework.dao.DataIntegrityViolationException:无法执行语句; SQL [n / a]; 约束[“在PUBLIC.PAGE(书名,章,卷,名称)上的UKOBQWYIY89PIIE6GP2NB4PVQ8W_INDEX_2值('acb0bb92-be2f-4dd3-9653-98f8d890e6b4',0、0,'Page0',1)”; SQL语句:
插入页面(book_id,章节,扩展名,名称,卷,id)值(?,??,?,?,?,?)[23505-197]]; 嵌套的异常是org.hibernate.exception.ConstraintViolationException:无法执行语句
您可以尝试deleteById
deleteById("9c7b2ab2-1c78-4e9f-adc5-99c7da42a7c6");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.