public interface BookRepository extends CrudRepository<Book, Long> {
long deleteByTitle(String title);
@Modifying
@Query("delete from Book b where b.title=:title")
void deleteBooks(@Param("title") String title);
}
public interface CategoryRepository extends CrudRepository<Category, Long> {}
构建初始数据
为了方便测试,我们先构建需要的数据schema.sql和data.sql:
CREATE TABLE book (
id BIGINT NOT NULL AUTO_INCREMENT,
title VARCHAR(128) NOT NULL,
category_id BIGINT,
PRIMARY KEY (id)
);
CREATE TABLE category (
id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(128) NOT NULL,
PRIMARY KEY (id)
);
insert into book(id,title,category_id)
values(1,'The Hobbit',1);
insert into book(id,title,category_id)
values(2,'The Rabbit',1);
insert into category(id,name)
values(1,'category');
测试
我们看一下怎么从Book中删除一条数据:
@Test
public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() {
assertThat(bookRepository.count()).isEqualTo(2);
bookRepository.deleteById(1L);
assertThat(bookRepository.count()).isEqualTo(1);
}
再看一下category的删除:
@Test
public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() {
categoryRepository.deleteAll();
assertThat(bookRepository.count()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(0);
}
再看一下book的删除:
@Test
public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() {
bookRepository.deleteAll();
assertThat(bookRepository.count()).isEqualTo(0);
assertThat(categoryRepository.count()).isEqualTo(1);
}