day20191010ClassNotes

笔记:

1.DAO模式组成部分:
程序 ----> 数据库
实体类 数据库中的表
工具类:公共的数据库连接、关闭、公共的增删改、查询
接口 : 程序提倡的是面向接口编程,从而降低程序的耦合性
实现类 : 通过不同的需求实现不同的接口

2.传统的Web应用组成分层( MVC 模式)
M : 模型 【 持久化对象(实体类) + DAO(数据访问层) + Service(业务访问层) 】
V : 视图 【客户端显示的页面(html,jsp,asp,php...)】
C : 控制层 【Servlet,前后台数据交互中转站】

3.使用JDBC操作数据库
   执行过程: Java程序和数据库之间的数据交互。

   数据库中的数据一一读取到程序(内存)中
   数据库方向: 数据库数据 ---> 库 ---> 表 ----> 数据类型 字段列

   程序方向: 程序 ----> 实体类-----> 数据类型 属性


4.DAO的设计模式
   实体类

5.使用JDBC操作数据库步骤
   5.1.加载驱动jar包
   5.2.写BaseUtils工具类
   5.3.实体类(遵循数据的一张表对应一个实体类)
   5.4.接口(CRUD:增删改查__查:根据条件查询)
   5.5.实现类
   5.6.测试类

6.单例模式
概念:
   一> 单例本身有且只有一个实例对象
   二> 单例类必须自己创建唯一的实例对象
   三> 单例类需要给其他实例对象提供调用该单例类的实例对象方法
单例主要解决的问题: 频繁的创建与消耗实例对象,节省内存资源消耗。

单例模式有哪些?
 懒汉式:
   优点 :等实例对象需要使用时再判断当前实例对象是否为空,不为空则返回,为空,则创建,节省内存资源;
   缺点: 多线程使用场景下,不安全
 饿汉式
   优点 : 线程安全
   缺点: 不管当前实例对象是否使用使用,加载时即创建实例,浪费内存资源

7.常见异常信息:

  1).You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'u.username = '??·?'AND u.password = '123'' at line 1:
sql语句错误

  2).java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
找到了1个问号,却插入了2个值,导致参数越界

  3).java.sql.SQLException: No value specified for parameter 2
缺少传递的占位符参数

8.进销存需求:

   1 )用户登录
   2 )退出登录 (JavaWeb的jsp数据交互)
   3 )销售
   4 )对销售记录进行分页查询并根据销售日期排序(降序)
   5 )根据商品名称查询该商品的库存数量


eclipse创建java project文件

 

 

 


 

sale.sql文件

 

 

 1 ##用户表
 2 CREATE TABLE `test`.`users`(  
 3   `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '用户id',
 4   `username` VARCHAR(20) NOT NULL COMMENT '用户名',
 5   `password` VARCHAR(20) NOT NULL COMMENT '密码',
 6   `realnam` VARCHAR(20) NOT NULL COMMENT '真实姓名',
 7   PRIMARY KEY (`id`)
 8 );
 9 
10 ##商品表
11 CREATE TABLE `test`.`product`(  
12   `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '商品 id',
13   `productname` VARCHAR(30) NOT NULL COMMENT '商品名称',
14   `quantity` INT(10) NOT NULL COMMENT '库存量',
15   PRIMARY KEY (`id`)
16 );
17 
18 ##销售记录表   从表
19 CREATE TABLE `test`.`sale`(  
20   `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '记录 id',
21   `price` DOUBLE(11,2) NOT NULL COMMENT '销售单价',
22   `quantity` INT(10) NOT NULL COMMENT '数量',
23   `totalprice` DOUBLE(10,2) NOT NULL COMMENT '总价',
24   `saledate` DATE NOT NULL COMMENT '销售日期',
25   `userid` INT(10) NOT NULL COMMENT '销售员 id,对应 users 表的主键',
26   `productid` INT(10) NOT NULL COMMENT '商品 id,对应 product 表的主键',
27   PRIMARY KEY (`id`),
28   CONSTRAINT `fk_uid` FOREIGN KEY (`userid`) REFERENCES `test`.`users`(`id`),
29   CONSTRAINT `fk_pid` FOREIGN KEY (`productid`) REFERENCES `test`.`product`(`id`)
30 );
31 
32 ##添加测试数据   ,先加主表再加从表
33 INSERT INTO users(username,PASSWORD,realnam) VALUES('小飞','123','***志飞')   ;
34 INSERT INTO users(username,PASSWORD,realnam) VALUES('小刘','223','刘鑫')   ;
35 INSERT INTO users(username,PASSWORD,realnam) VALUES('大刘','323','刘正')    ;
36 
37 
38 INSERT INTO product(productname,quantity) VALUES('可口可乐',200)  ;
39 INSERT INTO product(productname,quantity) VALUES('冰红茶',500)  ;
40 INSERT INTO product(productname,quantity) VALUES('咖啡',10000)  ;
41 
42 
43 INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(2,50,100,NOW(),1,1)  ;
44 INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(5,50,250,NOW(),2,2)  ;
45 INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(2,50,100,NOW(),3,1)  ;
46 INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(10,50,500,NOW(),3,3)  ;
47 INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(3,50,150,NOW(),2,1)  ;
48 INSERT INTO sale(price,quantity,totalprice,saledate,userid,productid) VALUES(6,50,300,NOW(),3,2)  ;
49 
50 
51 ## 三表连接查询  
52  SELECT s.id,price,s.quantity,totalprice,saledate,userid,productid,u.`realnam`,p.`productname` FROM sale s
53   LEFT JOIN users u ON u.`id` = s.`userid` 
54   LEFT JOIN product p ON p.`id` = s.`productid`
55   
56   ORDER BY s.`saledate` DESC
sale.sql

 


 

 

 

 

 

 

 

 utils包中放入BaseUtils.java文件夹中

    文件夹(写BaseUtils工具类):

  1 package com.kgc.kh76.utils;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DriverManager;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 import java.sql.SQLException;
  8 
  9 public class BaseUtils {
 10     // 定义连接数据库信息
 11     protected static final String DRIVER = "com.mysql.jdbc.Driver";
 12     protected static final String URL = "jdbc:mysql://127.0.0.1/test";
 13     protected static final String USER = "root";
 14     protected static final String PASSWORD = "ok";
 15 
 16     // 定义数据库连接对象、预编译sql语句传输通道、rs结果集
 17     protected Connection conn = null;
 18     protected PreparedStatement pstmt = null;
 19     protected ResultSet rs = null;
 20 
 21     // 加载驱动
 22     static {
 23         try {
 24             Class.forName(DRIVER);
 25         } catch (ClassNotFoundException e) {
 26             e.printStackTrace();
 27         }
 28     }
 29 
 30     // 创建数据库连接对象
 31     public Connection getConn() {
 32         try {
 33             return DriverManager.getConnection(URL, USER, PASSWORD);
 34         } catch (SQLException e) {
 35             e.printStackTrace();
 36         }
 37         return null;
 38     }
 39 
 40     // 关闭所有数据库连接对象
 41     public void closeAll() {
 42         try {
 43             if (rs != null) {
 44                 rs.close();
 45             }
 46             if (pstmt != null) {
 47                 pstmt.close();
 48             }
 49             if (conn != null) {
 50                 conn.close();
 51             }
 52         } catch (SQLException e) {
 53             e.printStackTrace();
 54         }
 55     }
 56 
 57     /**
 58      * 公共的查询方法
 59      * 
 60      * @param sql    传输的sql语句
 61      * @param params 预编译占位符参数
 62      * @return 查询的rs结果集
 63      */
 64     public ResultSet executeQuery(String sql, Object... params) {
 65         // 连接数据库
 66         conn = getConn();
 67         try {
 68             // 创建数据库传输通道
 69             pstmt = conn.prepareStatement(sql);
 70             // 循环遍历占位符参数
 71             for (int i = 0; i < params.length; i++) {
 72                 // 设置占位符参数
 73                 pstmt.setObject(i + 1, params[i]);
 74             }
 75             // 触发执行查询sql语句
 76             rs = pstmt.executeQuery();
 77         } catch (SQLException e) {
 78             e.printStackTrace();
 79         }
 80         return rs;
 81     }
 82     
 83     /**
 84      * 公共的增删改操作
 85      * @param sql        传输的sql语句
 86      * @param params     预编译占位符参数
 87      * @return            执行增删改操作受影响的行数
 88      */
 89     public int executeUpdate(String sql, Object... params) {
 90         // 连接数据库
 91         conn = getConn();
 92         // 执行增删改操作受影响的行数
 93         int result = 0;
 94         try {
 95             // 创建数据库传输通道
 96             pstmt = conn.prepareStatement(sql);
 97             // 循环遍历占位符参数
 98             for (int i = 0; i < params.length; i++) {
 99                 // 设置占位符参数
100                 pstmt.setObject(i + 1, params[i]);
101             }
102             // 触发执行增删改sql语句
103             result = pstmt.executeUpdate();
104         } catch (SQLException e) {
105             e.printStackTrace();
106         } finally {
107             // 调用关闭所有数据库连接对象
108             closeAll();
109         }
110         return result;
111     }
112 }
BaseUtils.java
 
 

Entitiy实体类(遵循数据的一张表对应一个实体类) :

  Product.java:

 1 package com.kgc.kh76.entity;
 2 
 3 public class Product {
 4     private int  id;         //INT(10) NOT NULL AUTO_INCREMENT COMMENT '商品 id',
 5     private String  productname; //VARCHAR(30) NOT NULL COMMENT '商品名称',
 6     private int  quantity;     //INT(10) NOT NULL COMMENT '库存量',
 7     public int getId() {
 8         return id;
 9     }
10     public void setId(int id) {
11         this.id = id;
12     }
13     public String getProductname() {
14         return productname;
15     }
16     public void setProductname(String productname) {
17         this.productname = productname;
18     }
19     public int getQuantity() {
20         return quantity;
21     }
22     public void setQuantity(int quantity) {
23         this.quantity = quantity;
24     }
25     
26     public Product() {
27     }
28     public Product(int id, String productname, int quantity) {
29         super();
30         this.id = id;
31         this.productname = productname;
32         this.quantity = quantity;
33     }
34     @Override
35     public String toString() {
36         return "Product [id=" + id + ", productname=" + productname + ", quantity=" + quantity + "]";
37     }
38 }
Product.java
 
 

Sale.java:

 1 package com.kgc.kh76.entity;
 2 
 3 public class Sale {
 4     private int id; // INT(10) NOT NULL AUTO_INCREMENT COMMENT '记录 id',
 5     private double price; // DOUBLE(11,2) NOT NULL COMMENT '销售单价',
 6     private int quantity; // INT(10) NOT NULL COMMENT '数量',
 7     private double totalprice; // DOUBLE(10,2) NOT NULL COMMENT '总价',
 8     private String saledate; // DATE NOT NULL COMMENT '销售日期',
 9 
10     private Users user; // INT(10) NOT NULL COMMENT '销售员 id,对应 users 表的主键',
11     private Product product; // INT(10) NOT NULL COMMENT '商品 id,对应 product 表的主键',
12     public int getId() {
13         return id;
14     }
15     public void setId(int id) {
16         this.id = id;
17     }
18     public double getPrice() {
19         return price;
20     }
21     public void setPrice(double price) {
22         this.price = price;
23     }
24     public int getQuantity() {
25         return quantity;
26     }
27     public void setQuantity(int quantity) {
28         this.quantity = quantity;
29     }
30     public double getTotalprice() {
31         return totalprice;
32     }
33     public void setTotalprice(double totalprice) {
34         this.totalprice = totalprice;
35     }
36     public String getSaledate() {
37         return saledate;
38     }
39     public void setSaledate(String saledate) {
40         this.saledate = saledate;
41     }
42     public Users getUser() {
43         return user;
44     }
45     public void setUser(Users user) {
46         this.user = user;
47     }
48     public Product getProduct() {
49         return product;
50     }
51     public void setProduct(Product product) {
52         this.product = product;
53     }
54     
55     public Sale() {
56     }
57     public Sale(int id, double price, int quantity, double totalprice, String saledate, Users user, Product product) {
58         this.id = id;
59         this.price = price;
60         this.quantity = quantity;
61         this.totalprice = totalprice;
62         this.saledate = saledate;
63         this.user = user;
64         this.product = product;
65     }
66     @Override
67     public String toString() {
68         return "Sale [id=" + id + ", price=" + price + ", quantity=" + quantity + ", totalprice=" + totalprice
69                 + ", saledate=" + saledate + ", user=" + user + ", product=" + product + "]";
70     }
71 }
Sale.java

 

Users.java:

 1 package com.kgc.kh76.entity;
 2 
 3 public class Users {
 4     private int id;             //INT(10) NOT NULL AUTO_INCREMENT COMMENT '用户id',
 5     private String username;     //VARCHAR(20) NOT NULL COMMENT '用户名',
 6     private String password;     //VARCHAR(20) NOT NULL COMMENT '密码',
 7     private String realnam;     //VARCHAR(20) NOT NULL COMMENT '真实姓名',
 8     public int getId() {
 9         return id;
10     }
11     public void setId(int id) {
12         this.id = id;
13     }
14     public String getUsername() {
15         return username;
16     }
17     public void setUsername(String username) {
18         this.username = username;
19     }
20     public String getPassword() {
21         return password;
22     }
23     public void setPassword(String password) {
24         this.password = password;
25     }
26     public String getRealnam() {
27         return realnam;
28     }
29     public void setRealnam(String realnam) {
30         this.realnam = realnam;
31     }
32     
33     public Users() {
34     }
35     public Users(int id, String username, String password, String realnam) {
36         this.id = id;
37         this.username = username;
38         this.password = password;
39         this.realnam = realnam;
40     }
41     @Override
42     public String toString() {
43         return "Users [id=" + id + ", username=" + username + ", password=" + password + ", realnam=" + realnam + "]";
44     }
45 }
Users.java

 


 

5.4.接口(CRUD:增删改查__查:根据条件查询)

dao文件夹接口

ProductDao.java

 1 package com.kgc.kh76.dao;
 2 
 3 import com.kgc.kh76.entity.Product;
 4 
 5 public interface ProductDao {
 6     // 对于商品表 减少库存
 7     // 根据商品id更新商品库存的方法
 8     int updateProductById(Product pro);
 9     
10     //根据商品名称查询该商品的库存数量
11     int productQuantity(String proName);
12 }
ProductDao.java

SaleDao.java

 1 package com.kgc.kh76.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.kgc.kh76.entity.Sale;
 6 
 7 public interface SaleDao {
 8     //添加销售记录表
 9     // 基本信息 : 商品名称  单价   数量
10     int addSale(Sale sale);
11     
12     //查询所有销售记录
13     //对销售记录进行分页查询并根据销售日期排序(降序)
14     List<Sale> queryAllSales();
15     
16     //根据销售记录ID修改销售记录信息
17     int updateSaleById(Sale sale);
18 }
SaleDao.java

UsersDao.java

 1 package com.kgc.kh76.dao;
 2 
 3 import com.kgc.kh76.entity.Users;
 4 
 5 public interface UsersDao {
 6     //根据用户名和密码查询方法
 7     Users queryUserByUnameAndPwd(String uname,String pwd);
 8     
 9     //强调: 一般项目,删除是很少应用的
10 }
UsersDao.java

 5.5.实现类dao包中的impl包

 

 

 

 1 package com.kgc.kh76.dao.impl;
 2 
 3 import java.sql.SQLException;
 4 
 5 import com.kgc.kh76.dao.ProductDao;
 6 import com.kgc.kh76.entity.Product;
 7 import com.kgc.kh76.utils.BaseUtils;
 8 
 9 public class ProductDaoImpl extends BaseUtils implements ProductDao {
10 
11     @Override
12     public int updateProductById(Product pro) {
13         String sql = " UPDATE `product` SET `productname` = ?,`quantity` = ? WHERE id = ? ";
14         Object[] params = {pro.getProductname(),pro.getQuantity(),pro.getId()};
15         return super.executeUpdate(sql, params);
16     }
17 
18     @Override
19     public int productQuantity(String proName) {
20         String sql = "SELECT  p.`quantity` FROM `product` p "
21                 + " WHERE p.`productname` = ? ";
22         rs = super.executeQuery(sql, new Object[] {proName});
23         //定义num数量
24         int num = 0;
25         try {
26             if(rs.next()) {
27                 num = rs.getInt("p.quantity");
28             }
29         } catch (SQLException e) {
30             e.printStackTrace();
31         }finally {
32             super.closeAll();
33         }
34         return num;
35     }
36 
37 }
ProductDaoImpl.java
 1 package com.kgc.kh76.dao.impl;
 2 
 3 import java.sql.SQLException;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import com.kgc.kh76.dao.SaleDao;
 8 import com.kgc.kh76.entity.Product;
 9 import com.kgc.kh76.entity.Sale;
10 import com.kgc.kh76.entity.Users;
11 import com.kgc.kh76.utils.BaseUtils;
12 
13 public class SaleDaoImpl extends BaseUtils implements SaleDao {
14 
15     @Override
16     public int addSale(Sale s) {
17         String sql = "INSERT INTO sale(price,quantity,"
18                 + "totalprice,saledate,userid,productid) VALUES(?,?,?,NOW(),?,?) ";
19         int addRes = super.executeUpdate(sql, new Object[] {s.getPrice(),s.getQuantity(),s.getTotalprice(),
20                 s.getUser().getId(),s.getProduct().getId()});
21         return addRes;
22     }
23 
24     @Override
25     public List<Sale> queryAllSales() {
26         //创建List<Sale>集合对象,用来存储数据库获取的rs结果集
27         List<Sale> sales = new ArrayList<Sale>();
28         //定义查询sql语句
29         StringBuffer sb = new StringBuffer();
30         sb.append("  SELECT s.id,price,s.quantity,totalprice,saledate,userid,productid,u.`realnam`,p.`productname` ");
31         sb.append("  FROM sale s ");
32         sb.append("   LEFT JOIN users u ON u.`id` = s.`userid`  ");
33         sb.append("   LEFT JOIN product p ON p.`id` = s.`productid` ");
34         sb.append("   ORDER BY s.`saledate` DESC ");
35         
36         //调用公共查询的方法
37         super.rs = super.executeQuery(sb.toString());
38         try {
39             //循环遍历rs结果集
40             while(rs.next()) {
41                 //创建Sale销售记录对象,将从数据循环遍历的数据赋值给实体类对象
42                 Sale sale = new Sale(rs.getInt("s.id"), 
43                                     rs.getDouble("price"),
44                                     rs.getInt("s.quantity"), 
45                                     rs.getDouble("totalprice"),
46                                     rs.getString("saledate"), 
47                                     new Users(rs.getInt("userid"), null, null, rs.getString("u.realnam")),
48                                     new Product(rs.getInt("productid"), rs.getString("p.productname"), 0));
49                 sales.add(sale);
50             }
51         } catch (SQLException e) {
52             e.printStackTrace();
53         }finally {
54             super.closeAll();
55         }
56         return sales;
57     }
58 
59     @Override
60     public int updateSaleById(Sale s) {
61         String sql = " UPDATE sale s SET s.`price` = ? ,s.`quantity` = ?,"
62                 + "    s.`totalprice` = ? ,s.`saledate` = ? , " + 
63                 "    s.`userid` = ? ,s.`productid` = ? WHERE s.`id` = ? ";
64         return super.executeUpdate(sql, new Object[] {s.getPrice(),s.getQuantity(),s.getTotalprice(),
65                                                     s.getSaledate(),s.getUser().getId(),
66                                                     s.getProduct().getId(),s.getId()});
67     }
68 
69 }
SaleDaoImpl.java
 1 package com.kgc.kh76.dao.impl;
 2 
 3 import java.sql.SQLException;
 4 
 5 import com.kgc.kh76.dao.UsersDao;
 6 import com.kgc.kh76.entity.Users;
 7 import com.kgc.kh76.utils.BaseUtils;
 8 
 9 public class UsersDaoImpl extends BaseUtils implements UsersDao {
10 
11     @Override
12     public Users queryUserByUnameAndPwd(String uname, String pwd) {
13         //创建Users对象,用来存储数据库返回的rs结果集数据
14         Users user = null;
15         String sql = "  SELECT * FROM users u WHERE u.username = ?  "
16                 + "    AND u.password = ?  ";
17         //创建Object参数数组,用来存储预编译占位符参数
18         Object[] params = {uname,pwd};
19         super.rs = super.executeQuery(sql, params);
20         try {
21             //遍历rs结果集
22             if(rs.next()) {
23                 user = new Users(rs.getInt("id"), 
24                                 rs.getString("username"), 
25                                 rs.getString("password"), 
26                                 rs.getString("realnam"));
27             }
28         } catch (SQLException e) {
29             e.printStackTrace();
30         }finally {
31             super.closeAll();
32         }
33         return user;
34     }
35 
36 }
UsersDaoImpl.java

   5.6.测试类test包

 

 

 

 1 package com.kgc.kh76.test;
 2 
 3 import com.kgc.kh76.dao.ProductDao;
 4 import com.kgc.kh76.dao.impl.ProductDaoImpl;
 5 import com.kgc.kh76.entity.Product;
 6 
 7 public class ProductDaoImplTest {
 8 
 9     public static void main(String[] args) {
10         ProductDao dao = new ProductDaoImpl();
11         /*String proName = "咖啡";
12         int num = dao.productQuantity(proName);
13         System.out.println(proName+"的数量是"+num+"件");*/
14         Product pro = new Product(2, "雪碧", 222222);
15         int updateRes = dao.updateProductById(pro);
16         System.out.println(updateRes);
17     }
18 }
ProductDaoImplTest.java
 1 package com.kgc.kh76.test;
 2 
 3 import com.kgc.kh76.dao.SaleDao;
 4 import com.kgc.kh76.dao.impl.SaleDaoImpl;
 5 import com.kgc.kh76.entity.Product;
 6 import com.kgc.kh76.entity.Sale;
 7 import com.kgc.kh76.entity.Users;
 8 
 9 public class SaleDaoImplDemo {
10 
11     public static void main(String[] args) {
12         SaleDao dao = new SaleDaoImpl();
13         
14         Sale sale = new Sale(1, 23, 999, 23*999,
15                 "2010-10-20", new Users(1, null, null, null), 
16                 new Product(2, null, 0));
17         int updateRes = dao.updateSaleById(sale);
18         System.out.println(updateRes);
19     }
20 }
SaleDaoImplDemo.java
 1 package com.kgc.kh76.test;
 2 
 3 import java.util.List;
 4 
 5 import com.kgc.kh76.dao.SaleDao;
 6 import com.kgc.kh76.dao.impl.SaleDaoImpl;
 7 import com.kgc.kh76.entity.Product;
 8 import com.kgc.kh76.entity.Sale;
 9 import com.kgc.kh76.entity.Users;
10 
11 public class SaleDaoImplTest {
12 
13     public static void main(String[] args) {
14         SaleDao dao = new SaleDaoImpl();
15         //新增
16         //创建Sale对象
17         Users user = new Users();
18         user.setId(3);
19         Product product = new Product();
20         product.setId(3);
21         Sale sale = new Sale(0, 11, 100, 1100, null, user, product);
22         int addRes = dao.addSale(sale);
23         System.out.println("addRes:"+addRes);
24         
25         
26         List<Sale> sales = dao.queryAllSales();
27         System.out.println("ID\t商品\t单价\t数量\t总价\t销售日期\t\t销售员\t");
28         for (Sale s : sales) {
29             System.out.println(s.getId()+"\t"+s.getProduct().getProductname()+
30                     "\t"+s.getPrice()+"\t"+s.getQuantity()+"\t"+s.getTotalprice()+
31                     "\t"+s.getSaledate()+"\t"+s.getUser().getRealnam());
32         }
33     }
34 
35 }
SaleDaoImplTest.java
 1 package com.kgc.kh76.test;
 2 
 3 import com.kgc.kh76.dao.UsersDao;
 4 import com.kgc.kh76.dao.impl.UsersDaoImpl;
 5 import com.kgc.kh76.entity.Users;
 6 
 7 public class UsersDaoImplTest {
 8 
 9     public static void main(String[] args) {
10         UsersDao dao = new UsersDaoImpl();
11         Users u = dao.queryUserByUnameAndPwd("小飞", "123");
12         
13         System.out.println(u);
14     }
15 
16 }
UsersDaoImplTest.java

singleton包

 

 

 1 package com.kgc.kh76.singleton;
 2 /*
 3  * 饿汉式单例
 4  */
 5 public class HungrySingleton {
 6     //私有化构造
 7     private HungrySingleton() {}
 8     
 9     //创建该单例
10     private static HungrySingleton singleton = new HungrySingleton();
11     
12     //给外部实例提供该单例模式的方法
13     public static HungrySingleton getInstance() {
14         return singleton;
15     }
16 }
HungrySingleton.java
 1 package com.kgc.kh76.singleton;
 2 /*
 3  * 懒汉式,一般使用单例模式之懒汉,解决线程不安全情况
 4  */
 5 public class LazySingleton {
 6     //创建该单例对象
 7     private static LazySingleton singleton = null;
 8     //私有化构造
 9     private LazySingleton() {}
10     
11     public static synchronized LazySingleton getIntance() {
12         if(null==singleton) {
13             singleton = new LazySingleton();
14         }
15         return singleton;
16     }
17     
18 }
LazySingleton.java
 1 package com.kgc.kh76.singleton;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         HungrySingleton hs = HungrySingleton.getInstance();
 7         System.out.println(hs);
 8         
 9         LazySingleton ls = LazySingleton.getIntance();
10         System.out.println(ls);
11     }
12 
13 }
Test.java


找对方法:

1.看懂当天课程所讲内容。+练习。

2.

3.

 

 

 

 








 

posted on 2019-10-23 17:16  xiaoluoke  阅读(126)  评论(0编辑  收藏  举报

导航