我们的第一个例子是简化的dao方式,主要是在编程中引入了oop概念。
这次,我们将dao补齐,但仍然保持最简单的形式,以便初学者学习。
简单的dao模式构成:
1 interface
2. factory
3 implements
4. caller
第一个例子中的主程序newsdao.java代码没有改动,只是改了个名字,
成为implements.
package news;
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,非常简单,因为我们只实现了一个方法,所以这儿也只有一个方法的申明,大家可以很容易地自己补上。
package news;
import java.sql.sqlexception;
public interface newsdao {
public news getnewsbyprimarykey(int newsid) throws sqlexception;
}
第三个程序是factory.
我们的环境比较简单,没有使用jndi,
package news;
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,没有任何改动,故不在此重复。
内网观测点:同第一例子。
更完整的例子,大家可以参考petstore 的catalogdao.
新闻热点
疑难解答