Our first example is the simplified DAO approach, which mainly introduces OOP concepts in programming.
This time, we'll make the DAO up, but still keep the simplest form for beginners to learn.
The simple DAO pattern consists of:
1 interface
2. Factory
3 Implements
4. Caller
The first example of the main program Newsdao.java code has not changed, just changed the name,
Become 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 = 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;
}
}
In addition to the first sentence by
The public class Newsdao became
public class Newsdaomysql implements Newsdao
The constructor name is changed from Newsdao () to Newsdaomysql (), which is no different from the first example.
The second program is interface, very simple, because we only implemented one method, so there is only one way to make a statement, you can easily fill up on their own.
package news;
import java.sql.SQLException;
public interface NewsDAO {
public News getNewsByPrimaryKey(int newsid) throws SQLException;
}
The third program is factory.
Our environment is relatively simple, not using 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;
}
}
Four, call the JSP program:
<%@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.");
%>
The POJO:News.java used in this case is not changed, so it is not repeated here.
Intranet observation point: Same as first example.
For a more complete example, you can refer to Petstore's Catalogdao.