3

I have a bunch of tables for which I need to provide standard CRUD interface. Every time I have to expose a new table, I follow the below pattern.

public interface EntityWithId<TDbEntity> extends Serializable {
    public TDbEntity entityId();
}

@Entity
public class DbEntityName implements EntityWithId<Long> {
    @Id private Long id;
    @Override public Long entityId() {return id;}

    // other fields follow
}

public class EntityName {
    private Long id;

    // other fields follow

    // create Entity from DbEntity
    public EntityName(DbEntityName dbItem) { ... }

    // get DbEntity from Entity
    public DbEntityName toDb() { ... }
}

@Repository
public interface DbEntityNameRepository extends CrudRepository<DbEntityName, Long> { }

public interface CrudService<TDbEntity extends EntityWithId<ID>, ID> {
    CrudRepository<TDbEntity, ID> getCrudRepository();

    // provide default implementation of all CRUD operations here like the below one
    default TDbEntity save(TDbEntity entity) { return getCrudRepository().save(entity); }
}


public interface DbEntityNameService extends CrudService<DbEntityName, Long> {
}

@Service
public class DbEntityNameServiceImpl implements DbEntityNameService {
    @lombok.Getter @Autowired DbEntityNameRepository crudRepository;
}

@RestController
@RequestMapping("/api/v1/dbservice")
public class EntityNameController {

    @Autowired DbEntityNameService dbService;

    @PostMapping("/{EntityName}") // this should be replaced by the actual name of the entity
    public Long save(@RequestBody EntityName msg) {
        return dbService.save(msg.toDb()).entityId();
    }

    // implement other CRUD end points
}

EntityWithId<T> interface and CrudService<TDbEntity extends EntityWithId<ID>, ID> are defined only once for the system. They provide mechanism to get rid of repeat code in accessing the repo.

As you will notice, the only real code needs to be done to add the fields in the Entity and the DB Entity, and their conversion. Also, I need to roll a new Controller out for each new table.

Question: How can I structure the controller code, in a way that I can inherit the functionality from a base CRUD controller.

Note that, in my real code not all entities are for simple CRUD, and the current structure provides easy way to extend the services

In a nutshell, I am looking for some pattern that will help me provide something like below, where I have a generic Base class, and I can create a subclass with minimal code to expose the controller's end point. Needless to say, the below code will not work as-is to provide the functionality I am looking for.

class BaseController<TEntity, TDbEntity, TId> {
    CrudService<TDbEntity, TId> dbService;

    @GetMapping("/{TEntity}/{id}")
    public TEntity getById(@PathVariable TId id) { 
        return new TEntity(dbService.getById(id));
    }

    @PostMapping("/{TEntity}")
    public Long save(@RequestBody TEntity msg) { 
        return dbService.save(msg.toDb()).entityId();
    }
}

class EntityNameController : BaseController<EntityName, DbEntityName, Long> {
}

Feel free to provide other suggestions too. My intention is to reduce repeated code in the controller - which is primarily creating the CRUD function, associating it with a CRUD endpoint and invoking the underlying service to do the real work.

EDIT: I understand that I can write a custom annotation processor to generate the standard CRUD functions (almost like how CrudRepository works), but that is not the direction I want to go.

Just to clarify, the intention here is that the standard functionality (like CRUD) can be coded once and for all in a base controller which will expose it, freeing up the child controller to take care of other non-standard work.

4
  • @PaulPearson That's what I am trying to figure out. How would such a code look like? How will the dbService get initialized. How will the GetMapping and PostMapping 'inherit', etc?
    – Vikhram
    Sep 9, 2019 at 16:45
  • 1
    Tbh this sounds like you should use Spring Data Rest. Basically you will have your repository expose all the standard endpoints and if needed you can add specified RepositoryControllers for the non-standard endpoints. Sep 10, 2019 at 8:28
  • @MirkoBrandt Thanks for the suggestion. I am reading up on it, and it looks like what I may be looking for. Trying to find if I can 1. Incorporate it without breaking the already exposed API (controlling the output JSON, and the URL endpoint).2. Add new custom handlers/endpoints in the controller (not in repo).
    – Vikhram
    Sep 10, 2019 at 16:14
  • @MirkoBrandt Unfortunately, I couldn't see how I can use Spring Data Rest for current situation. Even though Spring Data Rest provides a way to do what I am asking, it doesn't let me fine control the JSON to return. Also, it doesn't cleanly support the concept of api model and db model (we can hack it using the Jackson serializer/deserializer). The mechanism bypasses the service layer, and exposes the repo in the controller (which is great), but in my case I do bunch of validations, parsing, lookups, etc in my service layer
    – Vikhram
    Sep 11, 2019 at 12:34

2 Answers 2

1

I would think for the dbService you could use something like

public interface CrudService<T, ID> {

    T findByName(String name);

    Set<T> findAll();

    T findById(ID id);

    T save(T object);

    void delete(T object);

    void deleteById(ID id);

}

public interface EntityNameService extends CrudService<EntityName, Long> {
}


public class EntityNameServiceImpl implements EntityNameService {

    @Inject
    private DbEntityNameRepository repository;

    // implement all your repo code here
}

And your Base Controller could start like

public class BaseController {

    @Autowired
    private EntityNameService service;

    public String getEntityName(String name) {
        service.findByName(name);
    }

    @PostMapping("/{EntityName}") // this should be replaced by the actual name of the entity
    public Long save(@PathVariable String EntityName) {
        getEntityName(EntityName);
        return dbService.save(msg.toDb()).entityId();
    }

}
4
  • Can you develop the code more to show how the real controller would be? I already have in my question what you are presenting here in the answer.
    – Vikhram
    Sep 9, 2019 at 16:54
  • How do I avoid specifying the PostMapping in the child class? I want the base class to provide the functionality and the mapping.
    – Vikhram
    Sep 9, 2019 at 17:23
  • My intention is to reduce the "duplicate" code patterns in the controllers that I will end up creating one for each Table. The above approach so far doesn't suggest anything that will reduce the code. Using one controller for all the tables will also not reduce the code, but continue to harbor the repeated code patterns
    – Vikhram
    Sep 9, 2019 at 17:32
  • Your CrudService looks very close like the Spring Data JpaRepository: spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa Sep 11, 2019 at 18:39
1

This was an attempt at getting rid of some boiler plate. The idea was that the business logic would sit in the service and not in the RestController or Repository. A service could be reused and unit tested well.

QueryDSL with SpringData is your friend:

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-jpa</artifactId>
</dependency>

A base repo.

import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;

@NoRepositoryBean
public interface BaseRepo<T , ID > extends PagingAndSortingRepository<T, ID>, QuerydslPredicateExecutor<T> {}

The real repository that can access very large tables:

import com.querydsl.core.types.Predicate;
import static java.lang.System.out;
import refactor.BaseRepo;

public interface MyEntityRepository extends BaseRepo<MyEntity, String> {
    @Override
    default long count(Predicate predicate){
        //counts on very large tables take forever. Optionally add this
        return 0;
    }
    @Override
    default long count(){
        //counts on very large tables take forever. Optionally add this
        return 0;
    }    
}

The base service:

import com.querydsl.core.types.Predicate;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

@RequiredArgsConstructor
public class BaseService<T, ID> {

    final BaseRepo<T, ID> repo;

    public Page<T> findAll(Predicate predicate, Pageable pageable) {
        return repo.findAll(predicate, pageable);
    }

    public Iterable<T> findAllWithoutMeta(Predicate predicate, Pageable pageable) {
        return repo.findAll(predicate, pageable);
    }

    public Iterable<T> findAll() {
        return repo.findAll();
    }

    public T save(T vendor) {
        return repo.save(vendor);
    }

    public T update(T vendor) {
        return repo.save(vendor);
    }

    public void delete(ID id) {
        repo.deleteById(id);
    }

    public boolean exists(ID id) {
        return repo.findById(id).isPresent();
    }

    public Optional<T> getById(ID id) {
        return repo.findById(id);
    }

}

The real service:

import com.querydsl.core.types.Predicate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class MyService extends BaseService<MyEntity, String>{

    public MyService(MyEntityRepository repo) {
        super(repo);
    }

    @Override
    public Page<MyEntity> findAll(Predicate predicate, Pageable pageable) {
        return super.findAll(predicate, pageable); 
    }

}

I decided not to genrify my RestContoller and only write what I code I needed for the CRUD operations I needed. (In some cases delete and put operations are not needed or wanted for example) This is an implementation of a HATEOAS RESTful API. Investing in a HATEOAS design is not for everyone and every application. This can be substituted by a plain rest controller.

The get here can filter on all the fields in the repository. So you can get http://localhost/api/v1/myapi?name=YourName&age=30

import com.querydsl.core.types.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.binding.QuerydslPredicate;
import org.springframework.hateoas.EntityLinks;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path = "/api/v1/myapi", produces = MediaTypes.HAL_JSON_VALUE)
public class MyApiController {

    private final MyService service;
    private final EntityLinks eLinks;

    MyApiController(MyService service, EntityLinks eLinks) {
        this.service = service;
        this.eLinks = eLinks;
    }

    @GetMapping
    @Transactional(readOnly = true)
    ResponseEntity<Resources<Resource<MyEntity>>> findAll(@QuerydslPredicate(root = MyEntity.class) Predicate predicate, Pageable pageable) {
        return new ResponseEntity(toResources(service.findAllWithoutMeta(predicate,pageable)), HttpStatus.OK);
    }

    @GetMapping(value = "/{id}")
    ResponseEntity<Resource<MyEntity>> findOne(@PathVariable String id) {
        final Optional<MyEntity> findById = service.getById(id);
        if (!findById.isPresent()) {
            return null;//fixme ResponseEntity.notFound(assembler.);
        }
        return ResponseEntity.ok(toResource(findById.get()));
    }

    private Resources<Resource<MyEntity>> toResources(Iterable<MyEntity> customers) {
        List<Resource<MyEntity>> customerResources = new ArrayList<>();
        for (MyEntity l : customers) {
            customerResources.add(toResource(l));
        }

        return new Resources<>(customerResources);//, selfLink);

    }

    private Resource<MyEntity> toResource(MyEntity customer) {
        Link selfLink = linkTo(methodOn(CallLoggingController.class).findOne(customer.getId())).withSelfRel();
        return new Resource<>(customer, selfLink);

    }

}

My advice is do not to be obsessed with generic code. Copy and paste is better than super generic code imho.

1
  • Thanks @rjdkolb. I already have a very similar implementation, where my Repository and Services are streamlined without any major duplication. I am just unable to understand how I can reduce duplication of "code pattern" in Controller. I agree with your points though, and want to stay practical and reduce "work" when I have to expose a new table.
    – Vikhram
    Sep 11, 2019 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.