在Java SpringBoot中删除关系

huangapple 未分类评论54阅读模式
英文:

Deleting in relationships in Java SpringBoot

问题

以下是翻译好的内容:

开发者们,我在使用SpringBoot框架的应用程序中遇到了一个难题,我几乎无法解决。基本上,我无法将一个问题与如何在删除父项后删除关系中的一个项目联系起来。以下是我的解释:

首先,两个相互关联的实体:

产品子项

@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<>();

    // 产品实体的构造函数
    // -------------------------------------GETTERS和SETTERS---------------------------------
}

根据一个产品能够归类到多个类别的前提,这是产品实体与其之间关系的基础。然后:

类别父项

@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;

    // 类别实体的构造函数
    // ---------------------------GETTERS和SETTERS-----------------------------
}

按照前面的概念,但应用了向产品的类别关系的反向逻辑,并在我的数据库上完美运作。在存储库中,假设我这样设置:

类别存储库

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> {
}

产品存储库

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测试,就像这样:

类别实体

@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()'”。关于为什么会发生这种情况,有什么建议吗?提前谢谢!祝你有美好的一天!

英文:

Good Day developers , i'm hardly striving with this problem on my App which use SpringBoot framework.Basically can't put two and two together about how deleting one of the items in the relation ship once its parent is delete. Here my explanation:
First both entities with its respective relation to each other:

Product(Children)

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO,generator = &quot;native&quot;)
    @GenericGenerator(name=&quot;native&quot;,strategy=&quot;native&quot;)
    private Long id;

    @OneToMany(mappedBy = &quot;products&quot;,fetch= FetchType.EAGER,cascade = CascadeType.ALL, orphanRemoval = true)
    private Set&lt;Category&gt; categorySet= new HashSet&lt;&gt;();

    CONSTRUCTOR FOR PRODUCTS ENTITY 
-------------------------------------GETTERS AND SETTERS---------------------------------
 

Being this the Product entity under the premise of one product being able to clasify to several categories hence its relation OnetoMany.Then:

Categories(Parent)

@Entity
public class Category {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO,generator = &quot;native&quot;)
    @GenericGenerator(name=&quot;native&quot;,strategy=&quot;native&quot;)
    private Long id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name=&quot;product_id&quot;)
    private Product products;

    CONSTRUCTOR FOR CATEGORY ENTITY 

     ---------------------------GETTERS AND SETTERS-----------------------------

Following the former concept but withan inverse logic applied Category reltion toward products, and works perect on my database.
on repositories lets say i set this

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 &lt;Category,Long&gt; {
}

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&lt;Product,Long&gt; {
    Product findByProductName (String productName);
}

Then trying to set the command to delete products or categories from my Jpa and Crud Reps, using Junit Test on the Category Entity, like this:

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);
    }

Throws me an error saying that "Non-static method 'deleteAll()/count()' cannot be referenced from a static context".
Any idea about why this is happening .Any advice ?.Thanks in advance!!!!.Have a good day!!!

答案1

得分: 0

你正试图使用接口的非静态方法,但deleteAll()count()不是静态方法。尝试创建一个仓库对象,然后自动装配它以调用deleteAll()/count()方法。

@Autowired
private CategoryRepository categoryRepository;

并使用categoryRepository来调用deleteAll()/count()方法。

categoryRepository.deleteAll();
assert(categoryRepository.count()).isEqualTo(0);
英文:

You are try to use Non-static method of interface but deleteAll() or count() are not static method. Try to create a repository object then autowired it to call deleteAll() / count() method.

@Autowired
private CategoryRepository categoryRepository;

And use categoryRepository to call call deleteAll() / count() method

categoryRepository.deleteAll();
assert(categoryRepository.count()).isEqualTo(0);

答案2

得分: 0

尝试使用已实例化的 bean,即 CategoryRepository 和 ProductRepository,而不是接口。

英文:

Try using instantiated beans CategoryRepository and ProductRepository instead of the interfaces.

huangapple
  • 本文由 发表于 2020年4月8日 16:19:53
  • 转载请务必保留本文链接:https://java.coder-hub.com/61096303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定