gpt4 book ai didi

java - 对两列以上组合的唯一约束

转载 作者:行者123 更新时间:2023-12-02 00:59:41 25 4
gpt4 key购买 nike

我有两个表页面我试图在它们之间建立双向的一对多关系。

页面对多个列有唯一的约束,该约束无法正常工作。当我插入带有唯一 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: could not execute statement; SQL [n/a]; constraint ["UKOBQWYIY89PIIE6GP2NB4PVQ8W_INDEX_2 ON PUBLIC.PAGE(BOOK_ID, CHAPTER, VOLUME, NAME) VALUES ('acb0bb92-be2f-4dd3-9653-98f8d890e6b4', 0, 0, 'Page0', 1)"; SQL statement:

insert into page (book_id, chapter, extension, name, volume, id) values (?, ??, ?, ?, ?, ?) [23505-197]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

最佳答案

您可以尝试deleteById

  deleteById("9c7b2ab2-1c78-4e9f-adc5-99c7da42a7c6");

关于java - 对两列以上组合的唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57779884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com