[英]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.