【发布时间】:2020-07-20 14:32:33
【问题描述】:
Good Day 开发人员,我几乎不会在我的使用 SpringBoot 框架的应用程序上解决这个问题。基本上不能将两个和两个放在一起关于如何删除关系中的一个项目,一旦其父项被删除。这是我的解释: 首先是两个实体及其各自的相互关系:
Product(Children)
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator = "native")
@GenericGenerator(name="native",strategy="native")
private Long id;
@OneToMany(mappedBy = "products",fetch= FetchType.EAGER,cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Category> categorySet= new HashSet<>();
CONSTRUCTOR FOR PRODUCTS ENTITY
-------------------------------------GETTERS AND SETTERS---------------------------------
在一个产品能够分为多个类别的前提下,这是产品实体,因此它的关系是 OnetoMany.Then:
Categories(Parent)
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator = "native")
@GenericGenerator(name="native",strategy="native")
private Long id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="product_id")
private Product products;
CONSTRUCTOR FOR CATEGORY ENTITY
---------------------------GETTERS AND SETTERS-----------------------------
遵循前一个概念,但采用逆向逻辑,将类别关系应用于产品,并在我的数据库上完美运行。 在存储库上可以说我设置了这个
Category Repository
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.Collection;
@RepositoryRestResource
public interface CategoryRepository extends JpaRepository <Category,Long> {
}
Product Repository
package com.miniAmazon;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.*;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface ProductRepository extends CrudRepository<Product,Long> {
Product findByProductName (String productName);
}
然后尝试设置命令从我的 Jpa 和 Crud 代表中删除产品或类别,使用类别实体上的 Junit 测试,如下所示:
Category Entity
@Test
public static void whenDeletingCategories_thenProductsShouldAlsoBeDeleted() {
ProductRepository.deleteAll();
assert(CategoryRepository.count()).isEqualTo(0);
assert(ProductRepository.count()).isEqualTo(0);
}
@Test
public static void whenDeletingProducts_thenCategoriesShouldAlsoBeDeleted() {
CategoryRepository.deleteAll();
assert(CategoryRepository.count()).isEqualTo(0);
assert(ProductRepository.count()).isEqualTo(2);
}
向我抛出一个错误,提示“无法从静态上下文引用非静态方法 'deleteAll()/count()'”。 关于为什么会发生这种情况的任何想法。任何建议?提前谢谢!!!!。祝你有美好的一天!!!
【问题讨论】:
标签: java spring-boot jpa junit crud