DAO模式开发步骤
DAO模式开发
编写连接工厂ConnectionFactory,用来获取连接、返回连接对象。编写DBUtils处理关闭JDBC三个接口。
package com.li.jdbc.advanced; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; import com.mysql.jdbc.ConnectionGroupManager; public class ConnectionFactory { private static String DRIVER; private static String URL; private static String USER; private static String PASSWORD; /* 静态代码块,加载时只被执行一次 */ static { /* Properties存储的是键值对的map */ Properties props = new Properties(); InputStream is = ConnectionFactory.class.getResourceAsStream("jdbcinfo.properties"); try { /*读取流的信息,加载到类里面*/ props.load(is); DRIVER=props.getProperty("mysql.driver"); URL=props.getProperty("mysql.url"); USER=props.getProperty("mysql.user"); PASSWORD=props.getProperty("mysql.password"); } catch (IOException e) { e.printStackTrace(); } } public static Connection getConnection() { Connection conn=null; try { Class.forName(DRIVER); conn=DriverManager.getConnection(URL, USER, PASSWORD); } catch (Exception e) { } return conn; } /*作为测试的main方法*/ public static void main(String[] args) { System.out.println(ConnectionFactory.getConnection()); } }
编写数据库中对应的POJO类,从关系模型到对象模型的映射,如果是表结构是多表关系,那么也需要考虑类结构的单向或双向关系
例如,下面为一个订单的对象模型,里面包含了详细的订单项信息,我们可以通过订单访问订单项,同时我们也可以设置订单项对象模型访问对应的订单。
package com.li.pojo; import java.io.Serializable; /*应导入此包下面的Date*/ import java.sql.Date; import java.util.ArrayList; import java.util.List; public class Order implements Serializable { private static final long serialVersionUID = 7661403309178948735L; private Long id; private Date orderedDate; private Date shippedDate; private Double total; /*存储当前订单所有的订单明细*/ private List<OrderLine> orderlines = new ArrayList<OrderLine>(); public Order() {} public Order(Long id, Date orderedDate, Date shippedDate, Double total, List<OrderLine> orderlines ) { super(); this.id = id; this.orderedDate = orderedDate; this.shippedDate = shippedDate; this.total = total; this.orderlines=orderlines; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getOrderedDate() { return orderedDate; } public void setOrderedDate(Date orderedDate) { this.orderedDate = orderedDate; } public Date getshippedDate() { return shippedDate; } public void setshippedDate(Date shippedDate) { this.shippedDate = shippedDate; } public Double getTotal() { return total; } public