我使用单独的DAO类进行登录和注册,如下所示:
注册DAO:
public class RegistrationDAO {
public void insert(UserProfile user) {
try {
Connection con = DBConnection.getConnection();
String query = "insert into TBL_USER (USR_FIRST_NAME,USR_LST_NAME,USR_PRIMARY_EMAIL,USR_PASSWORD) values(?,?,?,?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, user.getFirstName());
pst.setString(2, user.getLastName());
pst.setString(3, user.getEmail());
pst.setString(4, user.getPassword());
pst.executeUpdate();
} catch (Exception e) {
System.out.println("@@@@Record insertion error in Registration DAO@@@@");
e.printStackTrace();
}
}
}
登录DAO:
public class LoginDAO {
public boolean authenticate(String email, String password)
throws Exception {
boolean isUser = false;
try {
Connection con = DBConnection.getConnection();
PreparedStatement statement = con.prepareStatement("select USR_PRIMARY_EMAIL, USR_PASSWORD from TBL_USER where USR_PRIMARY_EMAIL=? and USR_PASSWORD=?");
statement.setString(1, email);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
if (result.next()) {
isUser = true;
System.out.println("User authenticated successfully");
} else {
System.out.println("Invalid username or password!");
}
} catch (Exception e) {
System.out.println("DB related Error");
e.printStackTrace();
}
return isUser;
}
}
让我们说如果将来我的数据库从oracle更改为mySql,那么我应该能够连接。我开始知道DAO工厂和DAO接口必须用于连接多个数据库,但我无法确定如何在我的情况下应用它。
我是否需要分别为RegistatrationDao和LoginDao提供两个DAO接口?有什么更好的方法来实现这个目标?
答案 0 :(得分:3)
public interface LoginDAO {
public boolean authenticate(String email, String password) throws Exception;
}
public class OracleLoginDAOImpl implements LoginDAO {
public boolean authenticate(String email, String password) throws Exception {
//Oracle specific implementation goes here.
}
}
public class MySqlLoginDAOImpl implements LoginDAO {
public boolean authenticate(String email, String password) throws Exception {
//MySQL specific implementation goes here.
}
}
//NOW IN YOUR LOGIN Service
public class LoginService {
private LoginDAO loginDAO = new OracleLoginDAOImpl ();
//OR U CAN USE MYSQLDAO As BELOW
//private LoginDAO loginDAO = new MySqlLoginDAOImpl();
loginDAO.autheticate("user","password");
}
//同样为RegistrationDAO及其Oracle和MySQL实现类创建接口。