简体   繁体   中英

Should a DAO method call another method inside the same class or should the service layer do it?

I don't know if my question is clear enough, but imagine a situation where I need to delete an entity from the database.

If I'm using JPA's EntityManager.remove(Object object) , the object must be retrieved before being deleted.

To do so, I have a method called delete() , which receives an id, query for the entity calling another method called get() and then deletes it.

public Clazz delete(Integer key) {
    Clazz clazz = get(key);
    entityManager.remove(clazz);

    return clazz;
}

public Clazz get(Integer key) {
    return entityManager.find(Clazz.class, key);
}

I don't know if this is the right approach.

Should the call for the get() be at the Service layer, or that's the right way?

The "right way" really depends on what the user needs on the DAO interface.

If most of the time the user only has key to delete an object, it makes more sense to provide delete with key as a parameter. Or if we are not sure, we could also provide two overriding delete methods, one with key and other one with the object.

On a related topic, we could also consider the use of query to remove the object without getting it from the db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM