AzerDG
AzerDG

Reputation: 1

Generic service for Spring JPA inherited entities

I have a parent abstract class, which will act as a single table and hold all it's child classes data in it, example:

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

Child 1:

@Entity
@Getter
@Setter
@DiscriminatorValue("regular_user")
public class RegularUserEntity extends BaseUserEntity {

    @OneToMany(mappedBy = "user", fetch= FetchType.LAZY)
    private Set<File> files;
}

Child 2:

@Entity
@DiscriminatorValue("admin_user")
public class AdminUserEntity extends BaseUserEntity {

    @OneToMany(mappedBy = "admin", fetch= FetchType.LAZY)
    private Set<RegularUserEntity > regulatedUsers;
}

There are a dozen more child classes, and creating a service, repository and DTO converter for each one will be a lot of work, which I feel can be solved by some generic solution or interface. Does anyone have an idea for this?

Upvotes: 0

Views: 700

Answers (1)

Minh
Minh

Reputation: 83

My project use Spring data

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

}

Upvotes: 0

Related Questions