我正在研究 Java(Web)应用程序中数据库的 DAO 实现。只有我遇到了一个小问题。
我当前的代码:
帐户.java:
package beans;
public class Account {
private int accountId;
private String name;
private String password;
private String email;
public Account() {
}
public Account(final String name, final String password, final String email) {
this.name = name;
this.password = password;
this.email = email;
}
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
DAO.java:
package dao;
import java.util.Collection;
public interface DAO<T> {
public int insert(T t);
public boolean update(T t);
public T get();
public Collection<T> search();
public boolean delete(T t);
}
AccountDAO.java:
package dao;
import beans.Account;
import java.util.Collection;
public class AccountDAO implements DAO<Account> {
@Override
public int insert(Account t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean update(Account t) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Account get() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Account> search() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean delete(Account t) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
问题是我很确定我不想在DAO
界面中使用已经存在的 SQL 字符串,但是我遇到了如何正确实现的get()
问题search()
?
由于它是一个通用接口,我还不能使用列名,我想将get()
andsearch()
方法保留在接口中,以确保它们将被实现,除非确实需要从接口中删除它们。
我提出的建议是按范围或未完全填充的 T 类对象进行搜索。因此,如果您想获取 name=x 的帐户,那么您将拥有如下代码:
AccountDAO accountDAO = DAOFactory.getAccountDAO();
Account result = accountDAO.get(new Account(x, null, null));
但我不确定这是否是最好的解决方案,请帮助我。
问候。