我们的第一个例子是简化的DAO方式,主要是在编程中引入了oop概念。
这次,我们将DAO补齐,但仍然保持最简单的形式,以便初学者学习。
简单的DAO模式构成:
1 interface
2. Factory
3 Implements
4. caller
第一个例子中的主程序NewsDAO.java代码没有改动,只是改了个名字,
成为implements.
import java.sql.*;
public class NewsDAOMySQL implements NewsDAO {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/joke?user=root";
public NewsDAOMySQL() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (java.lang.ClassNotFoundException e) {
System.err.println("joke():" + e.getMessage());
}
}
public News getNewsByPrimaryKey(int newsid) throws SQLException {
Connection conn = null;
Statement stmt;
ResultSet rs;
News news = null;
String sql = "select newsid,title,content from news2"
+ " where newsid=" + newsid + "";
conn = getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
news = new News(rs.getInt(1), rs.getString(2), rs.getString(3));
}
rs.close();
stmt.close();
conn.close();
return news;
}
private Connection getConnection() throws SQLException {
Connection conn = null;
conn = DriverManager.getConnection(url);
return conn;
}
}
除了第一句由
public class NewsDAO 变成了
public class NewsDAOMySQL implements NewsDAO
构造方法名称由NewsDAO()变成NewsDAOMySQL(),这个程序与第一个例子并没有区别。
第二个程序是interface,非常简单,因为我们只实现了一个方法,所以这儿也只有一个方法的申明,大家可以很容易地
自己补上。
import java.sql.SQLException;
public interface NewsDAO {
public News getNewsByPrimaryKey(int newsid) throws SQLException;
}
第三个程序是Factory.
我们的环境比较简单,没有使用jndi,
public class NewsDAOFactory {
public static NewsDAO getDAO() throws Exception {
NewsDAO newsDao = null;
String className = "news.NewsDAOMySQL";
try {
newsDao = (NewsDAO) Class.forName(className).newInstance();
} catch (Exception se) {
}
return newsDao;
}
}
第四,调用的jsp程序:
<%@page contentType="text/html;charset=gb2312" %>
<%@page import="news.*" %>
<%
// old version on 2004-12-07
// NewsDAO newsDao = new NewsDAO();
// new version on 2004-12-21
NewsDAO newsDao = NewsDAOFactory.getDAO();
News news = newsDao.getNewsByPrimaryKey(1);
if(news != null) {
out.println("Title thru DAO:"+news.getTitle());
out.println("<br>");
out.println("Body:"+news.getContent());
}
else out.println("Failed.");
%>
第五,本例所使用的POJO:News.java,没有任何改动,故不在此重复。