Spring JPA继承实体的通用服务



我有一个父抽象类,它将作为一个表,并保存所有子类的数据在它,示例:

@Entity
@Table(name="users")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",
discriminatorType = DiscriminatorType.STRING)
public abstract class BaseUserEntity {
@Id
@Column(name = "id")
private UUID id;
private String email;
private String name;
}

儿童1:

@Entity
@Getter
@Setter
@DiscriminatorValue("regular_user")
public class RegularUserEntity extends BaseUserEntity {
@OneToMany(mappedBy = "user", fetch= FetchType.LAZY)
private Set<File> files;
}

儿童2:

@Entity
@DiscriminatorValue("admin_user")
public class AdminUserEntity extends BaseUserEntity {
@OneToMany(mappedBy = "admin", fetch= FetchType.LAZY)
private Set<RegularUserEntity > regulatedUsers;
}

还有十几个子类,为每个子类创建服务、存储库和DTO转换器将是大量的工作,我觉得可以通过一些通用的解决方案或接口来解决。有人对此有什么想法吗?

我的项目使用Spring数据

public class GenericService<E, ID extends Serializable> {
protected JpaRepository<E, ID> repository;
public GenericService(JpaRepository<E, ID> repository) {
this.repository = repository;
}
public Page<E> findAll(Pageable pageable) {
return repository.findAll(pageable);
}
public E findById(ID id) {
return repository.findById(id).get();
}
public E save(E entity) {
return repository.save(entity);
}
public void deleteById(ID id) {
repository.deleteById(id);
}
}
**Repository**
public interface ICategoryRepository extends JpaRepository<CategoryEntity, Integer> {
}
**Service class**
public class CategoryService extends GenericService<CategoryEntity, Integer> {
public final ICategoryRepository repository;
public CategoryService(ICategoryRepository repository) {
super(repository);
this.repository = repository;
}
public List<CategoryEntity> findAllActive() {
return repository.findAllActive(Sort.by(Sort.Direction.ASC, "name"));
}
}

最新更新