Java Web notes: DAO design mode and dao design mode

Source: Internet
Author: User

Java Web notes: DAO design mode and dao design mode
DAO Introduction

The full name of DAO is Data Access Object, a Data Access Object. Its main function is Data operations. It belongs to the Data layer operations in the standard development of programs. The development framework


The full name of the Business layer is Business Object, which can combine multiple atomic DAO operations to form a complete Business logic.

Data Layer: provides multiple atomic DAO operations, such as adding, deleting, and modifying. For some small systems, it is enough to use only the DAO mode. For large data systems, if there are many business associations, BO should be used for operations.


In the entire DAO design mode, operations are performed using interfaces. The client uses interfaces, and the server also uses interfaces to implement business logic. DAO consists of the following parts:

DatabaseConnection: Class responsible for opening and closing databases;

VO: mainly composed of attributes, setter, and getter. The attributes in VO correspond to the fields in the table. Each VO class object represents a record in the table;

DAO: mainly defines operation interfaces, database atomicity, addition, deletion, modification, query, and so on;

Impl: the real implementation class of the DAO interface to complete specific database operations, but is not responsible for opening or closing the database;

Proxy: Proxy implementation. It is responsible for opening and closing databases and calling real operations on class objects;

Factory: Get a DAO instantiated object through the Factory class.


Database creation

Create a table named emp with the following column names: empno, ename, job, hiredate, and sal.


Define the corresponding VO class

Emp. java

package com.zzh.test;import java.util.Date;public class Emp {private int empno;private String ename;private String job;private Date hiredate;private float sal;public int getEmpno() {return empno;}public void setEmpno(int empno) {this.empno = empno;}public String getEname() {return ename;}public void setEname(String ename) {this.ename = ename;}public String getJob() {return job;}public void setJob(String job) {this.job = job;}public Date getHiredate() {return hiredate;}public void setHiredate(Date hiredate) {this.hiredate = hiredate;}public float getSal() {return sal;}public void setSal(float sal) {this.sal = sal;}}

Database Connection class DatabaseConnection. java
Package com. zzh. test; import java. SQL. connection; import java. SQL. driverManager; public class DatabaseConnection {public static final String DBDRIVER = "com. mysql. jdbc. driver "; public static final String DBURL =" jdbc: mysql: // localhost: 3306/test "; public static final String DBUSER =" User Name "; public static final String DBPASS = "password"; private Connection conn = null; public DatabaseConnection () throws Exception {Try {Class. forName (DBDRIVER); this. conn = DriverManager. getConnection (DBURL, DBUSER, DBPASS);} catch (Exception e) {throw e;} public Connection getConnection () {return this. conn;} public void close () throws Exception {if (this. conn! = Null) {try {this. conn. close () ;}catch (Exception e) {throw e ;}}}}

Define DAO operation standard IEmpDAO. java
Package com. zzh. test; import java. util. list; public interface IEmpDAO {// defines the DAO operation standard/** database addition operation, which is generally named */public boolean doCreate (Emp emp) throws Exception in doXxx mode; /** database query operations, generally named in findXxx */public List <Emp> findAll (String keyWord) throws Exception; /** query information by Number */public Emp findById (int empno) throws Exception ;}

EmpDAOImpl. java
package com.zzh.test;import java.sql.Connection;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;import com.mysql.jdbc.PreparedStatement;public class EmpDAOImpl implements IEmpDAO {private Connection conn = null;private PreparedStatement pstmt = null;public EmpDAOImpl(Connection conn) {this.conn = conn;}@Overridepublic boolean doCreate(Emp emp) throws Exception {// TODO Auto-generated method stubboolean flag = false;String sql = "INSERT INTO emp(empno,ename,job,hiredate,sal)VALUES(?,?,?,?,?)";this.pstmt = (PreparedStatement) this.conn.prepareStatement(sql);this.pstmt.setInt(1, emp.getEmpno());this.pstmt.setString(2, emp.getEname());this.pstmt.setString(3, emp.getJob());this.pstmt.setDate(4, new java.sql.Date(emp.getHiredate().getTime()));this.pstmt.setFloat(5, emp.getSal());if (this.pstmt.executeUpdate() > 0) {flag = true;}this.pstmt.close();return flag;}@Overridepublic List<Emp> findAll(String keyWord) throws Exception {// TODO Auto-generated method stubList<Emp> all = new ArrayList<Emp>();String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE ename LIKE ? OR job LIKE ?";this.pstmt = (PreparedStatement) this.conn.prepareStatement(sql);this.pstmt.setString(1, "%" + keyWord + "%");this.pstmt.setString(2, "%" + keyWord + "%");ResultSet rs = this.pstmt.executeQuery();Emp emp = null;while (rs.next()) {emp = new Emp();emp.setEmpno(rs.getInt(1));emp.setEname(rs.getString(2));emp.setJob(rs.getString(3));emp.setHiredate(rs.getDate(4));emp.setSal(rs.getFloat(5));all.add(emp);}this.pstmt.close();return all;}@Overridepublic Emp findById(int empno) throws Exception {// TODO Auto-generated method stubEmp emp = null;String sql = "SELECT empno,ename,job,hiredate,sal FROM emp WHERE empno = ?";this.pstmt = (PreparedStatement) this.conn.prepareStatement(sql);this.pstmt.setInt(1, empno);ResultSet rs = this.pstmt.executeQuery();if (rs.next()) {emp = new Emp();emp.setEmpno(rs.getInt(1));emp.setEname(rs.getString(2));emp.setJob(rs.getString(3));emp.setHiredate(rs.getDate(4));emp.setSal(rs.getFloat(5));}this.pstmt.close();return emp;}}

Proxy topic implementation class EmpDAOProxy. java
package com.zzh.test;import java.util.*;import java.sql.*;public class EmpDAOProxy implements IEmpDAO {private DatabaseConnection dbc = null;private IEmpDAO dao = null;public EmpDAOProxy() throws Exception {this.dbc = new DatabaseConnection();this.dao = new EmpDAOImpl(this.dbc.getConnection());}public boolean doCreate(Emp emp) throws Exception {boolean flag = false;try {if (this.dao.findById(emp.getEmpno()) == null) {flag = this.dao.doCreate(emp);}} catch (Exception e) {throw e;} finally {this.dbc.close();}return flag;}public List<Emp> findAll(String keyWord) throws Exception {List<Emp> all = null;try {all = this.dao.findAll(keyWord);} catch (Exception e) {throw e;} finally {this.dbc.close();}return all;}public Emp findById(int empno) throws Exception {Emp emp = null;try {emp = this.dao.findById(empno);} catch (Exception e) {throw e;} finally {this.dbc.close();}return emp;}}

DAOFactory. java
package com.zzh.test;public class DAOFactory {public static IEmpDAO getIEmpDAOInstance() throws Exception {return new EmpDAOProxy();}}

Test the DAO insertion function TestDAOInsert. java
Package com. zzh. test; public class TestDAOInsert {public static void main (String [] args) throws Exception {Emp emp = null; for (int x = 0; x <5; x ++) {emp = new Emp (); emp. setEmpno (1000 + x); emp. setEname ("luna-" + x); emp. setJob ("Product Manager-" + x); emp. setHiredate (new java. util. date (); emp. setSal (500 * x); DAOFactory. getIEmpDAOInstance (). doCreate (emp );}}}
Running result:

Test query operations

TestDAOSelect. java

package com.zzh.test;import java.util.Iterator;import java.util.List;public class TestDAOSelect {public static void main(String[] args) throws Exception {// TODO Auto-generated method stubList<Emp> all = DAOFactory.getIEmpDAOInstance().findAll("");Iterator<Emp> iter = all.iterator();while (iter.hasNext()) {Emp emp = iter.next();System.out.println(emp.getEmpno() + ":" + emp.getEname() + "-->"+ emp.getEname());}}}
Running result:



JSP calls DAO to add data emp_insert.jsp
<% @ Page language = "java" contentType = "text/html; charset = GBK" pageEncoding = "GBK" %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 

Emp_insert_do.jsp
<% @ Page import = "java. text. simpleDateFormat "%> <% @ page import =" com. zzh. test. * "%> <% @ page language =" java "contentType =" text/html; charset = GBK "pageEncoding =" GBK "%> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 

Data Query operation emp_list.jsp
<% @ Page contentType = "text/html" pageEncoding = "GBK" %> <% @ page import = "java. text. simpleDateFormat "%> <% @ page import =" com. zzh. test. * "%> <% @ page import =" java. util. * "%> Running result:




Conclusion: Using the DAO + jsp development mode, we can find that java code in jsp is reduced. jsp mainly implements the function of outputting DAO running results, and the entire program logic needs to be well digested.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.