简体   繁体   中英

Spring Data JPA How to create single repository for two domain classes implementing a common interface?

I have two domain classes namely SubCategoryTierOne and SubCategoryTierTwo as described below :

@Entity
public class SubCategoryTierOne implements ISubCategory
{

   /** The id. */

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id;

   /** The name. */

   @NotNull
   private String name;

   /** The root. */

   @NotNull
   @ManyToOne
   private Category parent;

   /** The tier two sub categories. */
   @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)

//Getters and Setters
}

@Entity
public class SubCategoryTierTwo implements ISubCategory
{

   /** The id. */
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id;

   /** The name. */

   @NotNull
   private String name;

   /** The root. */

   @NotNull
   @ManyToOne
   private SubCategoryTierOne parent;

   /** The tier three sub categories. */
   @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
   private Set< SubCategoryTierThree > tierThreeSubCategories;

//Getters and Setters
}

So instead of creating seperate repositories for all these subcategories, I want to create a common repository, so all these domain classes implements a marker interface ISubCategory .

I created one repository like this :

public interface SubCategoryTierOneRepository<T extends ISubCategory> extends JpaRepository< ISubCategory, Long >
{

}

However when I run my application I get the following error :

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'subCategoryRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: interface com.kyac.learning.domain.ISubCategory

Can someone tell me where I am going wrong?

I understand the problem here, but are you sure you want to do something like this. you could rethink your design.

If I were you, I would go with something like this.

@Entity
public class Category  {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column
    private String description;

    @Column(nullable = false, unique = true)
    private String label;

    @ManyToOne(fetch = FetchType.LAZY)
    private Category parent;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
    private Set<Category> children = new HashSet<>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM