【问题标题】:Specify Ordering to a DAO Method为 DAO 方法指定排序
【发布时间】:2011-12-23 09:35:17
【问题描述】:

假设我有以下 DAO 接口:

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();
}

进一步假设我正在抽象这个 DAO,因为我可能提供 2 种实现,一种用于数据库,一种用于 Web 服务。

我想重载 getAll 方法以接受某种排序参数来指示返回值的排序方式。

但是,我不想将接口绑定到特定的实现。例如,数据库实现将使用 ORDER BY 子句,并且需要一个数据库列列表和一个顺序方向,例如“ASC”或“DESC”,而 Web 服务实现则不需要。

在不将调用者耦合到特定实现的情况下提供此类参数的最佳做法是什么?

编辑

对我的问题的小澄清。我不只是想指定一个参数来指示下单方向,还想指定什么下单。

例如,假设我的 Country 模型定义如下:

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;
    }

我希望返回的值按 name 升序排列。按照建议,我可以使用 ENUM 作为订单方向,但是在不暴露实现细节的情况下指定要订购的属性的最佳做法是什么?

【问题讨论】:

    标签: java dao


    【解决方案1】:

    布尔值:

    public List<Country> getAll(boolean ascending);
    

    或者一个枚举:

    enum SortOrder {
        ASCENDING,
        DESCENDING,
        RANDOM,
        NONE
    }
    
    public List<Country> getAll(SortOrder order);
    

    实际上实现这不是接口的工作。只需确保接口接受的任何输入都可以由您的任何一个类处理。

    【讨论】:

    • 通过ENUM指定下单方向其实是我想到的,但是在不具体实现的情况下如何指定模型上的哪些属性下单(例如,传递数据库列的名称) 到 DAO?我编辑了我的问题以反映我的需要。顺便感谢您的快速回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多