指定DAO方法的顺序 [英] Specify Ordering to a DAO Method
问题描述
假设我具有以下DAO界面:
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();
}
进一步假设我正在抽象此DAO,因为我可能会提供2种实现,一种
Further suppose that I am abstracting this DAO because I might provide 2 implementations, one for a database and one for a web service.
我想重载 getAll 方法以接受某种排序参数来指示返回值应排序。
I want to overload the getAll method to accept some sort of ordering parameter to indicate how the returned value should be ordered.
但是我不想将接口绑定到特定的实现。例如,一个数据库实现将使用ORDER BY子句,并且需要一个数据库列列表和一个顺序指示,例如 ASC或 DESC,而Web服务实现则不会。
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?
编辑
对我的问题的澄清不多。我不仅要指定一个参数来指示订购方向,还要要订购什么。
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;
}
我希望返回的值按 name 升序排列。如建议的那样,我可以使用ENUM作为顺序方向,但是在不公开实现细节的情况下指定要订购的属性的最佳方法是什么?
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?
推荐答案
布尔值之一:
public List<Country> getAll(boolean ascending);
或枚举:
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.
这篇关于指定DAO方法的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!