Specify Ordering to a DAO Method

六月ゝ 毕业季﹏ 提交于 2020-01-23 12:54:14

问题


Suppose I have the following DAO interface:

public interface CountryData {
    /**
     * Get All Countries.
     *
     * @return A Collection of Countries.
     * @throws DataAccessException Thrown if there is an error communicating with the data store. The Exception's
     *                             Cause Exception can usually be examined to determine the exact nature of the
     *                             error.
     * @since 1.0.0
     */
    public List<Country> getAll();
}

Further suppose that I am abstracting this DAO because I might provide 2 implementations, one for a database and one for a web service.

I want to overload the getAll method to accept some sort of ordering parameter to indicate how the returned value should be ordered.

I don't want to tie the interface to a specific implementation however. For example, a database implementation would use an ORDER BY clause and would need a list of database columns and an order direction such as "ASC" or "DESC" where is a web service implementation will not.

What's the best practice to provide such a parameter without coupling the caller to a specific implementation?

EDIT

Small clarification to my question. I don't just want to specify a parameter to indicate the order direction, but also what to order on.

For example, suppose my Country model was defined as follows:

public final class Country implements Serializable {
    private int id;
    private String name;

    public Country() {
    }

    public Country(Country countryToCopy) {
        this.id = countryToCopy.getId();
        this.name = countryToCopy.getName();
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

And I want to the returned value to be ordered by name in ascending order. I could use an ENUM, as suggested, for the order direction, but what would be the best practive to specify the property to order on without exposing implementation specifics?


回答1:


Either a boolean:

public List<Country> getAll(boolean ascending);

Or an enum:

enum SortOrder {
    ASCENDING,
    DESCENDING,
    RANDOM,
    NONE
}

public List<Country> getAll(SortOrder order);

Actually implementing this isn't the job of the interface. Just make sure any inputs the interface accepts can be handled by either of your classes.



来源:https://stackoverflow.com/questions/8033041/specify-ordering-to-a-dao-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!