Search code examples
javagenericsquarkusquarkus-panache

Java Quarkus, Create Generic CrudService


I want to create a java quarkus project by creating generic classes for myself except for the resource, so I don't have to implement the service and repository multiple times, just specify the entity classes and choose "standard" implementations. My error is that I get an exception when I want to add an object to the database, error: IllegalArgumentException: "Not an Entity" on TestEntity.

@ApplicationScoped
@Path("test")
@Tag(name = "Tests")
@Consumes("application/json")
@Produces("application/json")
public class TestResource{
    
    @Inject
    private TestService testService;

    @POST
    public Response create(TestEntity te){
        Optional<TestEntity> t = testService.create(te);
        return Response.status(Response.Status.OK).entity(t.get()).build();
    }
}

@RequestScoped
@Transactional
public interface IBaseService<TKey, TEntity> {
    
    public Optional<TEntity> create(TEntity entity);
}

@RequestScoped
@Transactional
public abstract class BaseService<TKey, TEntity> implements IBaseService<TKey, TEntity>{

    @Inject IBaseRepository<TKey, TEntity> repository;
    
    public BaseService(){

    }

    public Optional<TEntity> create(TEntity e) {
        Optional<TEntity> result = repository.create(e);
        if(result.isPresent()){
            return result;
        }
        return Optional.empty();
    }
}

@ApplicationScoped
public class TestService extends BaseService<UUID,TestEntity> {
}

public class TestEntity {
    public String s;
    public int i;
    public Object o;
}

@ApplicationScoped
public interface IBaseRepository<TKey, TEntity> {
    
    public Optional<TEntity> create(TEntity entity);
}

@ApplicationScoped
public interface ITestRepository extends IBaseRepository<UUID,TestEntity> {
}

@ApplicationScoped
public abstract class BaseRepository<TKey, TEntity, TEntityDB> implements IBaseRepository<TKey, TEntity>, PanacheRepositoryBase<TEntity, TKey>{
    
    public BaseRepository(){
    }

    @Override
    public Optional<TEntity> create(TEntity entity) {
        if(entity == null){
            return Optional.empty();
        }
        this.persist(entity);
        return Optional.of(entity);
    }
}

@ApplicationScoped
public class TestRepository extends BaseRepository<UUID, TestEntity,TestEntity> {
}

Solution

  • TestEntity is not an entity. You need to at least annotate it with @Entity