英文:
One @Service for multiple entities in Spring
问题
我有3个相关的实体:`Tag`、`SubcategoryTag`、`CategoryTag`,我想为所有3个实体创建一个共同的`@Service`。
我的Service应该是什么样子的?
public class Tag {
    @Id
    @GeneratedValue(generator = "optimized-sequence")
    @Column(name = "id")
    private Long id;
    @Column(name = "name", nullable = false, unique = true)
    private String name;
    @Enumerated(EnumType.STRING)
    @Column(name = "tag_type")
    private TagType tagType;
    @ManyToMany
    private Set<QuestionTemplate> questionTemplates;
}
Subcategory和Category继承自Tag
@Entity
@Inheritance(strategy = JOINED)
@Table(name = "T_TAG")
public class SubcategoryTag extends Tag {
    @ManyToOne(cascade = CascadeType.ALL, fetch = LAZY)
    private CategoryTag parentTag;
}
@Entity
@Inheritance(strategy = JOINED)
@Table(name = "T_TAG")
public class CategoryTag extends Tag {
    @OneToMany(orphanRemoval = true)
    private Set<SubcategoryTag> subcategoryTagSet;
}
英文:
I have 3 related entities Tag, SubcategoryTag, CategoryTag and I want to create a common @Service for all 3.
How should my Service look?
public class Tag {
    @Id
    @GeneratedValue(generator = "optimized-sequence")
    @Column(name = "id")
    private Long id;
    @Column(name = "name", nullable = false, unique = true)
    private String name;
    @Enumerated(EnumType.STRING)
    @Column(name = "tag_type")
    private TagType tagType;
    @ManyToMany
    private Set<QuestionTemplate> questionTemplates;
}
Subcategory and Category inherit from Tag
@Entity
@Inheritance(strategy = JOINED)
@Table(name = "T_TAG")
public class SubcategoryTag extends Tag {
    @ManyToOne(cascade = CascadeType.ALL, fetch = LAZY)
    private CategoryTag parentTag;
}
@Entity
@Inheritance(strategy = JOINED)
@Table(name = "T_TAG")
public class CategoryTag extends Tag {
    @OneToMany(orphanRemoval = true)
    private Set<SubcategoryTag> subcategoryTagSet;
}
答案1
得分: 0
创建三个实体的存储库
public interface TagRepo extends JpaRepository<Tag, Long>{}
public interface SubcategoryRepo extends JpaRepository<Subcategory, Long>{}
public interface CategoryTagRepo extends JpaRepository<CategoryTag,Long>{}
然后添加服务类并自动装配这三个存储库。
@Service
public class TagService {
    @Autowired
    TagRepo tagRepo;
    @Autowired
    SubcategoryRepo subcategoryRepo;
    @Autowired
    CategoryTagRepo categoryTagRepo;
    //添加您的方法
}
英文:
Create repositories for the three entities
public interface TagRepo extends JpaRepository<Tag, Long>{}
public interface SubcategoryRepo extends JpaRepository<Subcategory, Long>{}
public interface CategoryTagRepo extends JpaRepository<CategoryTag,Long>{}
then add the service class and Autowire the three repositories.
@Service
public class TagService {
    @Autowired
    TagRepo tagRepo;
    @Autowired
    SubcategoryRepo subcategoryRepo;
    @Autowired
    CategoryTagRepo categoryTagRepo;
    //Add your methods
    }
专注分享java语言的经验与见解,让所有开发者获益!

评论