Why use quarkus resources instead of services and controllers?

Well, maybe this is a beginner’s question, but I had trouble finding a clear explanation in the official documentation or other sources.

I’m a computer science student with just over a year and a half of programming experience. I’m more used to developing backend using spring boot, in which I usually use a structure of services and controllers, the services being responsible for the business logic and the controllers for the requests.

However, I’ve recently started to study Quarkus more. When looking at example code from the framework, I saw that instead of controllers, resources are used that join the controllers with the services. Basically, I don’t understand why I should do it this way instead of separating things, maybe I’m too used to the way I did it before, but I’d like to understand a little better what the advantages of this choice are, if it’s the best way (I know it depends a lot, but what factors influence this decision) and well, are there any risks in terms of the responsibilities of each layer when applying this way of developing?

Well, that’s it, I’d really appreciate it if you could help me with that!

Well, in terms of what I’ve done, I’m just studying and I think this is more theoretical content. But here’s a generic feature I’ve implemented, basically I did it this way to make basic crud operations easier. But one thing you might notice is that the resource has direct access to the entity, is this correct when thinking about encapsulation, security and the responsibility of the layers? How could I improve it?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>package com.dotgrupo.generic.resource;
import com.dotgrupo.exception.EntityNotFoundException;
import com.dotgrupo.generic.entity.GenericEntity;
import com.dotgrupo.generic.utils.Updatable;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;
import java.util.List;
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public abstract class GenericResource<T extends GenericEntity> {
private final Class<T> entityClass;
@Inject
EntityManager entityManager;
public GenericResource(final Class<T> entityClass) {
this.entityClass = entityClass;
}
@GET
@Operation(summary = "Get all entities", description = "Returns a list of all entities.")
@APIResponses(value = {
@APIResponse(responseCode = "200", description = "List of entities returned successfully."),
@APIResponse(responseCode = "500", description = "Internal server error.")
})
public List<T> getAll() {
return entityManager.createQuery("FROM " + entityClass.getSimpleName(), entityClass).getResultList();
}
@GET
@Path("{id}")
@Operation(summary = "Get an entity by ID", description = "Returns the entity corresponding to the provided ID.")
@APIResponses(value = {
@APIResponse(responseCode = "200", description = "Entity found."),
@APIResponse(responseCode = "404", description = "Entity not found.")
})
public T get(@PathParam("id") Long id) {
T entity = entityManager.find(entityClass, id);
if (entity == null) {
throw new EntityNotFoundException("Entity with id " + id + " does not exist.");
}
return entity;
}
@POST
@Transactional
@Operation(summary = "Create a new entity", description = "Creates a new entity.")
@APIResponses(value = {
@APIResponse(responseCode = "201", description = "Entity created successfully."),
@APIResponse(responseCode = "400", description = "Error in entity creation.")
})
public Response create(T entity) {
entity.id = null;
entityManager.persist(entity);
return Response.status(Response.Status.CREATED).entity(entity).build();
}
@PUT
@Path("{id}")
@Transactional
@Operation(summary = "Update an existing entity", description = "Updates the entity corresponding to the provided ID.")
@APIResponses(value = {
@APIResponse(responseCode = "200", description = "Entity updated successfully."),
@APIResponse(responseCode = "404", description = "Entity not found.")
})
public Response update(@PathParam("id") Long id, T entity) {
T existingEntity = entityManager.find(entityClass, id);
if (existingEntity == null) {
throw new EntityNotFoundException("Entity with id " + id + " does not exist.");
}
updateEntity(existingEntity, entity);
entityManager.merge(existingEntity);
return Response.ok(existingEntity).build();
}
@DELETE
@Path("{id}")
@Transactional
@Operation(summary = "Delete an entity", description = "Deletes the entity corresponding to the provided ID.")
@APIResponses(value = {
@APIResponse(responseCode = "204", description = "Entity deleted successfully."),
@APIResponse(responseCode = "404", description = "Entity not found.")
})
public Response delete(@PathParam("id") Long id) {
T entity = entityManager.find(entityClass, id);
if (entity == null) {
throw new EntityNotFoundException("Entity with id " + id + " does not exist.");
}
entityManager.remove(entity);
return Response.noContent().build();
}
protected void updateEntity(T existingEntity, T newEntity) {
Updatable.updateProperties(existingEntity, newEntity);
}
}
</code>
<code>package com.dotgrupo.generic.resource; import com.dotgrupo.exception.EntityNotFoundException; import com.dotgrupo.generic.entity.GenericEntity; import com.dotgrupo.generic.utils.Updatable; import jakarta.inject.Inject; import jakarta.persistence.EntityManager; import jakarta.transaction.Transactional; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.openapi.annotations.Operation; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; import java.util.List; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public abstract class GenericResource<T extends GenericEntity> { private final Class<T> entityClass; @Inject EntityManager entityManager; public GenericResource(final Class<T> entityClass) { this.entityClass = entityClass; } @GET @Operation(summary = "Get all entities", description = "Returns a list of all entities.") @APIResponses(value = { @APIResponse(responseCode = "200", description = "List of entities returned successfully."), @APIResponse(responseCode = "500", description = "Internal server error.") }) public List<T> getAll() { return entityManager.createQuery("FROM " + entityClass.getSimpleName(), entityClass).getResultList(); } @GET @Path("{id}") @Operation(summary = "Get an entity by ID", description = "Returns the entity corresponding to the provided ID.") @APIResponses(value = { @APIResponse(responseCode = "200", description = "Entity found."), @APIResponse(responseCode = "404", description = "Entity not found.") }) public T get(@PathParam("id") Long id) { T entity = entityManager.find(entityClass, id); if (entity == null) { throw new EntityNotFoundException("Entity with id " + id + " does not exist."); } return entity; } @POST @Transactional @Operation(summary = "Create a new entity", description = "Creates a new entity.") @APIResponses(value = { @APIResponse(responseCode = "201", description = "Entity created successfully."), @APIResponse(responseCode = "400", description = "Error in entity creation.") }) public Response create(T entity) { entity.id = null; entityManager.persist(entity); return Response.status(Response.Status.CREATED).entity(entity).build(); } @PUT @Path("{id}") @Transactional @Operation(summary = "Update an existing entity", description = "Updates the entity corresponding to the provided ID.") @APIResponses(value = { @APIResponse(responseCode = "200", description = "Entity updated successfully."), @APIResponse(responseCode = "404", description = "Entity not found.") }) public Response update(@PathParam("id") Long id, T entity) { T existingEntity = entityManager.find(entityClass, id); if (existingEntity == null) { throw new EntityNotFoundException("Entity with id " + id + " does not exist."); } updateEntity(existingEntity, entity); entityManager.merge(existingEntity); return Response.ok(existingEntity).build(); } @DELETE @Path("{id}") @Transactional @Operation(summary = "Delete an entity", description = "Deletes the entity corresponding to the provided ID.") @APIResponses(value = { @APIResponse(responseCode = "204", description = "Entity deleted successfully."), @APIResponse(responseCode = "404", description = "Entity not found.") }) public Response delete(@PathParam("id") Long id) { T entity = entityManager.find(entityClass, id); if (entity == null) { throw new EntityNotFoundException("Entity with id " + id + " does not exist."); } entityManager.remove(entity); return Response.noContent().build(); } protected void updateEntity(T existingEntity, T newEntity) { Updatable.updateProperties(existingEntity, newEntity); } } </code>
package com.dotgrupo.generic.resource;

import com.dotgrupo.exception.EntityNotFoundException;
import com.dotgrupo.generic.entity.GenericEntity;
import com.dotgrupo.generic.utils.Updatable;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponse;
import org.eclipse.microprofile.openapi.annotations.responses.APIResponses;

import java.util.List;

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public abstract class GenericResource<T extends GenericEntity> {
    private final Class<T> entityClass;

    @Inject
    EntityManager entityManager;

    public GenericResource(final Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    @GET
    @Operation(summary = "Get all entities", description = "Returns a list of all entities.")
    @APIResponses(value = {
            @APIResponse(responseCode = "200", description = "List of entities returned successfully."),
            @APIResponse(responseCode = "500", description = "Internal server error.")
    })
    public List<T> getAll() {
        return entityManager.createQuery("FROM " + entityClass.getSimpleName(), entityClass).getResultList();
    }

    @GET
    @Path("{id}")
    @Operation(summary = "Get an entity by ID", description = "Returns the entity corresponding to the provided ID.")
    @APIResponses(value = {
            @APIResponse(responseCode = "200", description = "Entity found."),
            @APIResponse(responseCode = "404", description = "Entity not found.")
    })
    public T get(@PathParam("id") Long id) {
        T entity = entityManager.find(entityClass, id);
        if (entity == null) {
            throw new EntityNotFoundException("Entity with id " + id + " does not exist.");
        }
        return entity;
    }

    @POST
    @Transactional
    @Operation(summary = "Create a new entity", description = "Creates a new entity.")
    @APIResponses(value = {
            @APIResponse(responseCode = "201", description = "Entity created successfully."),
            @APIResponse(responseCode = "400", description = "Error in entity creation.")
    })
    public Response create(T entity) {
        entity.id = null;
        entityManager.persist(entity);
        return Response.status(Response.Status.CREATED).entity(entity).build();
    }

    @PUT
    @Path("{id}")
    @Transactional
    @Operation(summary = "Update an existing entity", description = "Updates the entity corresponding to the provided ID.")
    @APIResponses(value = {
            @APIResponse(responseCode = "200", description = "Entity updated successfully."),
            @APIResponse(responseCode = "404", description = "Entity not found.")
    })
    public Response update(@PathParam("id") Long id, T entity) {
        T existingEntity = entityManager.find(entityClass, id);
        if (existingEntity == null) {
            throw new EntityNotFoundException("Entity with id " + id + " does not exist.");
        }
        updateEntity(existingEntity, entity);
        entityManager.merge(existingEntity);
        return Response.ok(existingEntity).build();
    }

    @DELETE
    @Path("{id}")
    @Transactional
    @Operation(summary = "Delete an entity", description = "Deletes the entity corresponding to the provided ID.")
    @APIResponses(value = {
            @APIResponse(responseCode = "204", description = "Entity deleted successfully."),
            @APIResponse(responseCode = "404", description = "Entity not found.")
    })
    public Response delete(@PathParam("id") Long id) {
        T entity = entityManager.find(entityClass, id);
        if (entity == null) {
            throw new EntityNotFoundException("Entity with id " + id + " does not exist.");
        }
        entityManager.remove(entity);
        return Response.noContent().build();
    }

    protected void updateEntity(T existingEntity, T newEntity) {
        Updatable.updateProperties(existingEntity, newEntity);
    }
}

I don’t know if my implementation helps you understand my question, but I hope so!

New contributor

chagas_m is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật