Java web实训项目:西蒙购物网

文章目录

一、创建数据库和表

1、创建数据库

  • 数据库 - simonshop
    在这里插入图片描述

2、创建用户表

创建用户表结构 - t_user
在这里插入图片描述

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) DEFAULT NULL,
  `telephone` varchar(11) DEFAULT NULL,
  `register_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `popedom` int(11) DEFAULT NULL COMMENT '0:管理员;1:普通用户',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

  • 在用户表里插入记录
    在这里插入图片描述
INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2021-12-02 08:40:35', '0');
INSERT INTO `t_user` VALUES ('2', '郑晓红', '11111', '13956567889', '2022-12-20 09:51:43', '1');
INSERT INTO `t_user` VALUES ('3', '温志军', '22222', '13956678907', '2022-12-20 09:52:36', '1');
INSERT INTO `t_user` VALUES ('4', '涂文艳', '33333', '15890905678', '2022-12-05 09:52:56', '1');

3、创建类别表

  • 创建类别表结构 - t_category

在这里插入图片描述

CREATE TABLE `t_category` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品类别标识符',
  `name` varchar(100) NOT NULL COMMENT '商品类别名称',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

  • 在类别表里插入记录
    在这里插入图片描述
INSERT INTO `t_category` VALUES ('1', '家用电器');
INSERT INTO `t_category` VALUES ('2', '床上用品');
INSERT INTO `t_category` VALUES ('3', '文具用品');
INSERT INTO `t_category` VALUES ('4', '休闲食品');

4、创建商品表

  • 创建商品表结构 - t_product
    在这里插入图片描述
CREATE TABLE `t_product` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品标识符',
  `name` varchar(200) NOT NULL COMMENT '商品名称',
  `price` double DEFAULT NULL COMMENT '商品单价',
  `add_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `category_id` int(11) DEFAULT NULL COMMENT '商品类别标识符',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;

  • 在商品表里插入记录
    在这里插入图片描述
INSERT INTO `t_product` VALUES ('1', '容声电冰箱', '2000', '2016-12-20 09:54:41', '1');
INSERT INTO `t_product` VALUES ('2', '松下电视', '5000', '2016-12-20 09:54:35', '1');
INSERT INTO `t_product` VALUES ('3', '红岩墨水', '3', '2016-12-20 09:56:05', '3');
INSERT INTO `t_product` VALUES ('4', '海尔洗衣机', '1000', '2016-11-30 08:58:09', '1');
INSERT INTO `t_product` VALUES ('5', '新宇电饭煲', '1200', '2016-12-20 09:55:11', '1');
INSERT INTO `t_product` VALUES ('6', '英雄微波炉', '600', '2016-12-20 09:55:39', '1');
INSERT INTO `t_product` VALUES ('7', '红双喜席梦思', '700', '2016-11-28 08:59:38', '2');
INSERT INTO `t_product` VALUES ('8', '旺仔牛奶糖', '24.4', '2016-12-20 10:00:11', '4');
INSERT INTO `t_product` VALUES ('9', '西蒙枕头', '100', '2016-12-20 09:56:57', '2');
INSERT INTO `t_product` VALUES ('10', '甜甜毛毯', '400', '2016-12-20 09:57:26', '2');
INSERT INTO `t_product` VALUES ('11', '永久钢笔', '50', '2016-12-20 09:57:30', '3');
INSERT INTO `t_product` VALUES ('12', '硬面抄笔记本', '5', '2016-12-20 09:57:53', '3');
INSERT INTO `t_product` VALUES ('13', '晨光橡皮擦', '0.5', '2016-11-30 09:02:40', '3');
INSERT INTO `t_product` VALUES ('14', '美的空调', '3000', '2016-11-03 09:03:02', '1');
INSERT INTO `t_product` VALUES ('15', '迷你深海鱼肠', '14.4', '2016-12-02 10:01:14', '4');

5、创建订单表

创建订单表结构 - t_order
在这里插入图片描述

CREATE TABLE `t_order` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '订单标识符',
  `username` varchar(20) DEFAULT NULL COMMENT '用户名',
  `telephone` varchar(11) DEFAULT NULL COMMENT '电话号码',
  `total_price` double DEFAULT NULL COMMENT '总金额',
  `delivery_address` varchar(50) DEFAULT NULL COMMENT '送货地址',
  `order_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '下单时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

  • 在订单表里插入记录
    在这里插入图片描述
INSERT INTO `t_order` VALUES ('1', '郑晓红', '13956567889', '2000', '泸职院信息工程系', '2016-12-25 17:12:36');
INSERT INTO `t_order` VALUES ('2', '温志军', '13956678907', '1000', '泸职院机械工程系', '2016-12-02 17:12:17');

二、创建Simonshop项目

1、创建web项目

在这里插入图片描述

  • 创建项目名称与保存位置
    在这里插入图片描述
  • 单机【finsh】
    在这里插入图片描述

2、修改Artifacts名称:simonshop

  • 将Artifact名称改为simonshiop
    在这里插入图片描述

3、重新部署项目

在这里插入图片描述

  • 切换到【server】选项卡
    在这里插入图片描述

4、编辑首页

  • 首页 - index.jsp
<%@ page import="java.util.Date" %><%--
  Created by IntelliJ IDEA.
  User: HW
  Date: 2023/5/29
  Time: 15:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
  <h1 style="color: blue; text-align:center">Java Web实训项目:西蒙购物网</h1>
  <h3 style="text-align: center"><%= new Date()%></h3>
  <p style="text-align: center"><a href="login.jsp">跳转到登录界面</a> </p>
  </body>
</html>

5、启动应用,查看效果

在这里插入图片描述

三、创建实体类

  • 创建四个实体类:UserCategoryProductOrder

1、用户实体类

  • 创建ner.xyx.shop.bean包,在包里创建用户实体类 - User
    在这里插入图片描述
package net.xyx.shop.bean;

import java.util.Date;

public class User {
    private int id;//用户标识符
    private String username;//用户名
    private String password;//密码
    private String telephone;//电话
    private Date registerTime;//注册时间
    private int popedom;//权限(0:管理员;1:普通用户)

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    public int getPopedom() {
        return popedom;
    }

    public void setPopedom(int popedom) {
        this.popedom = popedom;
    }

    @Override
    public String toString(){
        return "User{" +
                "id=" + id +
                ",password=" + password +
                ",telephone= " + telephone +
                ",registerTime=" + registerTime +
                ",popedom=" + popedom + '\'' +
                '}';
    }
}

2、创建类别实体类

  • 创建ner.xyx.shop.bean包,在包里创建订单实体类 - Category
    在这里插入图片描述
package net.xyx.shop.bean;

public class Category {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public  String toString(){
        return "Category{" +
                "id=" + id +
                ",name=" + name + '\'' +
                '}';
    }
}

3、创建商品实体类

  • 创建ner.xyx.shop.bean包,在包里创建订单实体类 - Category
    在这里插入图片描述
package net.xyx.shop.bean;

import java.util.Date;

public class Product {
    private int id;
    private String name;
    private double price;
    private Date addTime;
    private int categotyId;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Date getAddTime() {
        return addTime;
    }

    public void setAddTime(Date addTime) {
        this.addTime = addTime;
    }

    public int getCategotyId() {
        return categotyId;
    }

    public void setCategotyId(int categotyId) {
        this.categotyId = categotyId;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", addTime=" + addTime +
                ", categotyId=" + categotyId +
                '}';
    }
}

``
## 4、创建订单实体类
- 创建`ner.xyx.shop.bean`包,在包里创建订单实体类 - `Order`
![在这里插入图片描述](https://img-blog.csdnimg.cn/b878bc1b6af54665b8004a45058e69d7.png)
- 代码如下
```xml
package net.xyx.shop.bean;

import java.util.Date;

public class Order {
    private int id;
    private String username;
    private String telehpone;
    private double totalPrice;
    private String deliveryAddress;
    private Date orderTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getTelehpone() {
        return telehpone;
    }

    public void setTelehpone(String telehpone) {
        this.telehpone = telehpone;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public String getDeliveryAddress() {
        return deliveryAddress;
    }

    public void setDeliveryAddress(String deliveryAddress) {
        this.deliveryAddress = deliveryAddress;
    }

    public Date getOrderTime() {
        return orderTime;
    }

    public void setOrderTime(Date orderTime) {
        this.orderTime = orderTime;
    }

    @Override
    public String toString() {
        return "Order{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", telehpone='" + telehpone + '\'' +
                ", totalPrice=" + totalPrice +
                ", deliveryAddress='" + deliveryAddress + '\'' +
                ", orderTime=" + orderTime +
                '}';
    }
}


三、创建数据库工具类

1、添加数据库驱动程序包

  • 在\WEB-INF里创建lib子目录,添加MySQL驱动程序的
    在这里插入图片描述
  • 将数据库驱动程序包作为库添加到项目

2、创建数据库连接管理类

  • 创建net.xyx.shop.dbutil包,在里面创建ConnectionManager
    在这里插入图片描述
  • 原代码


3、测试数据库连接是否成功

4、数据库连接的常见错误

(1)、数据库驱动程序名称写错误

(2)、数据库没找到

5、创建数据访问接口

(1)、创建用户数据访问接口

  • net.xyx.shop根包里创建dao子包,在子包里创建UserDao接口

在这里插入图片描述


package net.xyx.shop.dao;

import net.xyx.shop.bean.User;

import java.util.List;

public interface UserDao {
    int insert(User user);//插入用户
    int deleteById(int id);//按标识符删除用户
    int update(User user);//更新用户
    User findById(int id);//按标识符查询用户
    List<User> findByUsername(String username);//按用户名查找用户
    List<User> findAll();//查询全部用户
    User login (String username,String password);//用户登录
}

(2)、类别数据访问接口CaregoryDao

  • net.xyx.shop根包里创建dao子包,在子包里创建CaregoryDao接口

在这里插入图片描述

package net.xyx.shop.dao;

import net.xyx.shop.bean.Category;

import java.util.List;

/**
 * 功能:类别数据访问接口
 * 作者:XYX
 */

public interface CategoryDao {
    int insert(Category category);//插入类别
    int deleteById(int id);//按标识符删除类别
    int update(Category category);//更新类别
    Category findById(int id);//按标识符查询类别
    List<Category>findAll();//查询全部类别
}


(3)、创建商品数据访问接口ProductDao

  • net.xyx.shop根包里创建dao子包,在子包里创建ProductDao接口
    在这里插入图片描述
package net.xyx.shop.dao;

import net.xyx.shop.bean.Product;

import java.util.List;

public interface ProductDao {
    int insert(Product product);//插入商品
    int deleteById(int id);//按标识符删除商品
    int update(Product product);//更新商品
    Product findById(int id);//按标识符查询商品
    List<Product> findByCategoryId (int categoryId);//按类别标识符查询商品
    List<Product> findAll();//查询全部商品
}


(4)、订单数据访问接口OrderDao

  • net.xyx.shop根包里创建dao子包,在子包里创建OrderDao接口
    在这里插入图片描述
package net.xyx.shop.dao;

import net.xyx.shop.bean.Order;

import java.util.List;

public interface OrderDao {
    int insert(Order order);//插入订单
    int deleteById(int id);//按标识符删除订单
    int update(Order order);//更新订单
    Order findById(int id);//按标识符查询订单
    Order findLast();//查询左后一个订单
    List<Order>findAll();//查询全部订单
}

6、数据访问接口实现类DaoImpl

(1)、创建用户数据访问接口实现类

  • net.xyx.shop.dao包里创建impl子包,在子包里创建UserDaoImpl
    在这里插入图片描述
  • 实现UserDao接口

在这里插入图片描述

① 编写插入用户方法
    @Override//插入用户方法
    public int insert(User user) {
        //定义插入记录数
        int count = 0;

        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            //定义SQL字符串
            String strSQL = "INSERT INTO t_user (username,password, telephone, register_time, popedom) VALUES(?,?,?,?,?)";
            //创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setString(1,user.getUsername());
            pstmt.setString(2,user.getPassword());
            pstmt.setString(3,user.getTelephone());
            pstmt.setTimestamp(4,new Timestamp(user.getRegisterTime().getTime()));
            pstmt.setInt(5,user.getPopedom());
            //执行更新操作,插入新记录
            count = pstmt.executeUpdate();
            //关闭预备语句对象
            pstmt.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);//关闭数据库连接
        }

        //返回插入记录
        return count;
    }
②边界删除用户方法
@Override//按标识删除用户
    public int deleteById(int id) {
        //定义删除记录数
        int count = 0;

        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            //定义SQL字符串
            String strSQL = "DELETE FROM t_user WHERE id=?";
            //创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setInt(1,id);
            //执行更新操作,插入新记录
            count = pstmt.executeUpdate();
            //关闭预备语句对象
            pstmt.close();
        }catch (SQLException e) {
           System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);//关闭数据库连接
        }

        //返回删除记录数
        return count;
    }
③编写更新用户方法
@Override//按标识符更新用户
    public int update(User user) {
        //定义更新用户记录数
        int count = 0;

        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            //定义SQL字符串
            String strSQL = "UPDATE t_user SET username=?,password=?, telephone=?, register_time = ?, popedom=?," +
                    "WHERE id = ?";
            //创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setString(1,user.getUsername());
            pstmt.setString(2,user.getPassword());
            pstmt.setString(3,user.getTelephone());
            pstmt.setTimestamp(4,new Timestamp(user.getRegisterTime().getTime()));
            pstmt.setInt(5,user.getPopedom());
            pstmt.setInt(6,user.getId());
            //执行更新操作,更新记录
            count = pstmt.executeUpdate();
            //关闭预备语句对象
            pstmt.close();
        }catch (SQLException e) {
           System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);//关闭数据库连接
        }


        //返回更新记录数
        return count;
    }
④编写按标识符查询用户方法
@Override//按标识符查询用户方法
    public User findById(int id) {
        // 定义查询用户
        User user = null;

        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            //定义SQL字符串
            String strSQL = "SELECT * FROM t_user WHERE id=?";
            //创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setInt(1,id);
            //执行查询操作,返回结果集
            ResultSet rs = pstmt.executeQuery();
            //判断结果集是否为空
            if (rs.next()){
                //创建用户对象
                user = new User();
                //设置用户对象属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
                user.setPopedom(rs.getInt("popedom"));
            }
            //关闭预备语句对象
            pstmt.close();
        }catch (SQLException e) {
           System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);//关闭数据库连接
        }

        //返回查询用户
        return user;
    }
⑤编写按用户名查询用户的方法
@Override//按用户名查询用户
    public List<User> findByUsername(String username) {
        //定义用户列表
        List<User> users = new ArrayList<>();

        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            //定义SQL字符串
            String strSQL = "SELECT * FROM t_user WHERE username=?";
            //创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setString(1,username);
            //执行查询操作,返回结果集
            ResultSet rs = pstmt.executeQuery();
            //判断结果集是否为空
            while (rs.next()){
                //创建用户对象
                 User user = new User();
                //设置用户对象属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
                user.setPopedom(rs.getInt("popedom"));
                //将用户对象添加到用户列表
                users.add(user);
            }
            //关闭预备语句对象
            pstmt.close();
        }catch (SQLException e) {
           System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);//关闭数据库连接
        }
        
        //返回用户列表
        return users;
    }
⑥编写查询全部用户方法
@Override//查询所有用户
    public List<User> findAll() {

        //定义用户列表
        List<User> users = new ArrayList<>();

        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            //定义SQL字符串
            String strSQL = "SELECT * FROM t_user";
            //创建语句对象
            Statement stmt = conn.createStatement();
            //执行查询操作,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            //判断结果集是否为空
            while (rs.next()){
                //创建用户对象
                User user = new User();
                //设置用户对象属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
                user.setPopedom(rs.getInt("popedom"));
                //将用户对象添加到用户列表
                users.add(user);
            }
            //关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);//关闭数据库连接
        }

        //返回用户列表
        return users;
    }
⑦编写登录方法
@Override//登录方法
    public User login(String username, String password) {
        //定义查询用户
        User user = null;

        //获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            //定义SQL字符串
            String strSQL = "SELECT * FROM t_user WHERE username = ? and password = ?";
            //创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setString(1,username);
            pstmt.setString(1,password);
            //执行查询操作,返回结果集
            ResultSet rs = pstmt.executeQuery();
            //判断结果集是否为空
            if (rs.next()){
                //创建用户对象
                user = new User();
                //设置用户对象属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
                user.setPopedom(rs.getInt("popedom"));
            }
            //关闭预备语句对象
            pstmt.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);//关闭数据库连接
        }

        //返回查询用户
        return user;
    }

在这里插入图片描述

(2)、对用户数据访问接口实现类做单元测试

在这里插入图片描述

  • 于是项目里有了一个绿色的测试文件夹 - test
    在这里插入图片描述
  • test文件夹里创建net.xyx.shop.dao.impl包,在里面创建TestUserDaoImpl
    在这里插入图片描述
①编写测试登录方法
  • 给测试方法添加@Test注解,会报错
    在这里插入图片描述
  • 添加单元测试JUnit项目,将光标移到@test注解上,按Alter+Enter键

在这里插入图片描述

  • 单击【Add ‘JUnit4’ to classpath】
    在这里插入图片描述
  • 单击【OK】按钮
    在这里插入图片描述
  • 运行testLogin()方法,查看效果
package net.xyx.shop.dao.impl;

import net.xyx.shop.bean.User;
import net.xyx.shop.dao.UserDao;
import org.junit.Test;

/**
 * 测试用户数据访问接口实现类
 */
public class TestUserDaoImpl {
    @Test
    public void testLogin(){
        String username = "admin";
        String password = "12345";

        //创建用户数据访问接口对象
        UserDao userDao = new UserDaoImpl();//用父接口变量指向子类对象
        //调用用户数据访问接口对象的登录方法
        User user = userDao.login(username,password);
        //判断用户是否登录成功
        if (user != null) {//成功
            System.out.println("恭喜," + username + ",登录成功~");
        }else{//失败
            System.out.println("遗憾," + username + ",登录失败~");
        }
    }
}

②编写按标识符查询用户方法
@Test //测试按标识符查询用户方法
    public void testFindById(){
        //定义从标识符变量
        int id = 2;
        //创建用户数据访问接口对象
        UserDao userDao = new UserDaoImpl();
        //调用用户数据访问接口对昂的按标识符查询用户方法
        User user = userDao.findById(id);
        //判断是否找到指定用户
        if (user != null){//找到
            System.out.println(user);
        }else{//未找到
            System.out.println("编号为【" + id + "】的用户为找到~");
        }
  • 运行testFindById()方法,查看结果
    在这里插入图片描述
③编写按用户名查询用户方法
@Test //测试按用户名查询用户
    public void testFindByUsername(){
        //定义用户名变量
        String username = "郑晓红";
        //创建用户数据访问接口对象
        UserDao userDao = new UserDaoImpl();
        //调用用户数据访问接口对象的按用户名查询用户方法
        List<User> users = userDao.findByUsername(username);
        //判断是否找到
        if(users.size() > 0){//找到
            users.forEach(user -> System.out.println(user));
        }else{//未找到
            System.out.println("没有找到名为[" + username + "]的用户");
        }
    }
  • 运行testFindByUsername()方法,查看结果
  • 修改待查用户名,在运行测试方法,查看结果
    在这里插入图片描述
④编写查询全部用户方法
  • testFindAll()
@Test//测试查询全部用户
    public void testFindAll(){
        //创建用户数据访问接口对象
        UserDao userDao=new UserDaoImpl();
        //调用用户数据访问接口对象查询全部用户方法
        List<User> users=userDao.findAll();
        if(users.size()>0){
            users.forEach(user -> System.out.println(user));
        }else {
            System.out.println("用户表里面没有记录");
        }
    }
⑤编写测试插入用户方法
 @Test //测试插入用户
    public void testInsert(){
        //创建用户对象
        User user = new User();
        //设置用户对象属性
        user.setUsername("易烊千玺");
        user.setPassword("1128");
        user.setTelephone("12345678342");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        //创建用户数据访问接口对象
        UserDao userDao = new UserDaoImpl();
        //调用用户数据访问接口对象的插入用户方法
        int count = userDao.insert(user);
        //判断是否成功插入用户
        if (count>0) {//成功
            System.out.println("恭喜,插入用户记录成功~");
        }else{//失败
            System.out.println("遗憾,插入用户失败~");
        }
    }
  • 运行testInsert()方法,查看结果
    在这里插入图片描述
  • 在Navitcaat里查看用户表
    在这里插入图片描述
⑥编写测试更新用户方法
@Test//测试更新用户
    public void testUpdate(){
        //创建用户对象
        User user = new User();
        //设置用户对象属性
        user.setId(5);
        user.setUsername("刘艳芬");
        user.setPassword("1343");
        user.setTelephone("13728678342");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        //创建用户数据访问接口对象
        UserDao userDao = new UserDaoImpl();
        //调用用户数据访问接口对象的更新用户方法
        int count = userDao.update(user);
        //判断是否成功更新用户
        if(count > 0){//成功
            System.out.println("恭喜,更新用户记录成功~");
        }else{
            System.out.println("遗憾,更新用户失败~");
        }
    }
  • 运行testUpdate() 方法,查看结果
⑦编写测试删除用户方法
@Test//测试删除用户
    public void testDelete(){
        //定义标识符变量
        int id = 6;
        //创建用户数据访问接口对象
        UserDao userDao = new UserDaoImpl();
        //调用用户数据访问接口对象的删除用户方法
        int count = userDao.deleteById(id);
        //判断是否成功删除用户
        if(count > 0){//成功
            System.out.println("恭喜,删除用户成功~");
        }else{
            System.out.println("遗憾,删除用户失败~");
        }
    }
  • 运行testDelete()方法,查看结果
    在这里插入图片描述
  • 在Navicat里查看记录,id为6的记录没有了
    在这里插入图片描述
  • 若想再次插入记录下一次生成的是id为7的记录

(3)、创建类别数据访问接口实现类

  • net.xyx.shop.dao.impl包里创建CategoryDaoImpl
①编写插入类别方法
@Override // 插入类别                                                        
public int insert(Category category) {                                   
    // 定义插入记录数                                                           
    int count = 0;                                                       
                                                                         
    // 获得数据库连接                                                           
    Connection conn = ConnectionManager.getConnection();                 
    // 定义SQL字符串                                                          
    String strSQL = "INSERT INTO t_category (name) VALUES (?)";          
    try {                                                                
        // 创建预备语句对象                                                      
        PreparedStatement pstmt = conn.prepareStatement(strSQL);         
        // 设置占位符的值                                                       
        pstmt.setString(1, category.getName());                          
        // 执行更新操作,插入新录                                                   
        count = pstmt.executeUpdate();                                   
        // 关闭预备语句对象                                                      
        pstmt.close();                                                   
    } catch (SQLException e) {                                           
        System.err.println(e.getMessage());                              
    } finally {                                                          
        ConnectionManager.closeConnection(conn); // 关闭数据库连接              
    }                                                                    
                                                                         
    // 返回插入记录数                                                           
    return count;                                                        
}                                                                        
②编写按标识符插入类别方法
@Override // 按标识符删除类别                                              
public int deleteById(int id) {                                    
    // 定义删除记录数                                                     
    int count = 0;                                                 
                                                                   
    // 获得数据库连接                                                     
    Connection conn = ConnectionManager.getConnection();           
    // 定义SQL字符串                                                    
    String strSQL = "DELETE FROM t_category WHERE id = ?";         
    try {                                                          
        // 创建预备语句对象                                                
        PreparedStatement pstmt = conn.prepareStatement(strSQL);   
        // 设置占位符的值                                                 
        pstmt.setInt(1, id);                                       
        // 执行更新操作,删除记录                                             
        count = pstmt.executeUpdate();                             
        // 关闭预备语句对象                                                
        pstmt.close();                                             
    } catch (SQLException e) {                                     
        System.err.println(e.getMessage());                        
    } finally {                                                    
        ConnectionManager.closeConnection(conn); // 关闭数据库连接        
    }                                                              
                                                                   
    // 返回删除记录数                                                     
    return count;                                                  
}                                                                  

③编写更新类别方法
@Override // 更新类别                                                     
public int update(Category category) {                                
    // 定义更新记录数                                                        
    int count = 0;                                                    
                                                                      
    // 获得数据库连接                                                        
    Connection conn = ConnectionManager.getConnection();              
    // 定义SQL字符串                                                       
    String strSQL = "UPDATE t_category SET name = ? WHERE id = ?";    
    try {                                                             
        // 创建预备语句对象                                                   
        PreparedStatement pstmt = conn.prepareStatement(strSQL);      
        // 设置占位符的值                                                    
        pstmt.setString(1, category.getName());                       
        pstmt.setInt(2, category.getId());                            
        // 执行更新操作,更新记录                                                
        count = pstmt.executeUpdate();                                
        // 关闭预备语句对象                                                   
        pstmt.close();                                                
    } catch (SQLException e) {                                        
        System.err.println(e.getMessage());                           
    } finally {                                                       
        ConnectionManager.closeConnection(conn); // 关闭数据库连接           
    }                                                                 
                                                                      
    // 返回更新记录数                                                        
    return count;                                                     
}                                                                     

④编写按标识符查询方法
@Override // 按标识符查询类别                                                   
public Category findById(int id) {                                      
    // 声明类别                                                             
    Category category = null;                                           
                                                                        
    // 获取数据库连接对象                                                        
    Connection conn = ConnectionManager.getConnection();                
    // 定义SQL字符串                                                         
    String strSQL = "SELECT * FROM t_category WHERE id = ?";            
    try {                                                               
        // 创建预备语句对象                                                     
        PreparedStatement pstmt = conn.prepareStatement(strSQL);        
        // 设置占位符的值                                                      
        pstmt.setInt(1, id);                                            
        // 执行SQL查询,返回结果集                                                
        ResultSet rs = pstmt.executeQuery();                            
        // 判断结果集是否有记录                                                   
        if (rs.next()) {                                                
            // 实例化商品类别                                                  
            category = new Category();                                  
            // 利用当前记录字段值去设置商品类别的属性                                      
            category.setId(rs.getInt("id"));                            
            category.setName(rs.getString("name"));                     
        }                                                               
    } catch (SQLException e) {                                          
        System.err.println(e.getMessage());                             
    } finally {                                                         
        ConnectionManager.closeConnection(conn); // 关闭数据库连接             
    }                                                                   
                                                                        
    // 返回类别                                                             
    return category;                                                    
}                                                                       

⑤编写查询全部方法
@Override // 查询全部类别                                                           
public List<Category> findAll() {                                             
    // 声明类别列表                                                                 
    List<Category> categories = new ArrayList<Category>();                    
                                                                              
    // 获取数据库连接对象                                                              
    Connection conn = ConnectionManager.getConnection();                      
    // 定义SQL字符串                                                               
    String strSQL = "SELECT * FROM t_category";                               
    try {                                                                     
        // 创建语句对象                                                             
        Statement stmt = conn.createStatement();                              
        // 执行SQL,返回结果集                                                        
        ResultSet rs = stmt.executeQuery(strSQL);                             
        // 遍历结果集                                                              
        while (rs.next()) {                                                   
            // 创建类别实体                                                         
            Category category = new Category();                               
            // 设置实体属性                                                         
            category.setId(rs.getInt("id"));                                  
            category.setName(rs.getString("name"));                           
            // 将实体添加到类别列表                                                     
            categories.add(category);                                         
        }                                                                     
        // 关闭结果集                                                              
        rs.close();                                                           
        // 关闭语句对象                                                             
        stmt.close();                                                         
    } catch (SQLException e) {                                                
        System.err.println(e.getMessage());                                   
    } finally {                                                               
        ConnectionManager.closeConnection(conn); // 关闭数据库连接                   
    }                                                                         
                                                                              
    // 返回类别列表                                                                 
    return categories;                                                        
}                                                                             

(4)、 对类别数据访问接口对象做单元测试

  • 在测试文件夹的net.xyx.shop.dao.impl包里创建TestCategoryDaoImpl
①编写测试按标识符查询类别方法
 @Test // 测试按标识符查询类别
    public void testFindById() {
        // 定义标识符变量
        int id = 1;
        // 创建类别数据访问接口对象
        CategoryDao categoryDao = new CategoryDaoImpl();
        // 调用类别数据访问接口对象的按标识符查询类别方法
        Category category = categoryDao.findById(id);
        // 判断是否找到指定类别
        if (category != null) { // 找到
            System.out.println(category);
        } else { // 未找到
            System.out.println("编号为[" + id + "]的类别未找到~");
        }
    }
②编写测试查询全部类别方法
@Test // 测试查询全部类别                                                         
public void testFindAll() {                                               
    // 创建类别数据访问接口对象                                                       
    CategoryDao categoryDao = new CategoryDaoImpl();                      
    // 调用类别数据访问接口对象的查询全部类别方法                                              
    List<Category> categories = categoryDao.findAll();                    
    // 判断是否有类别                                                            
    if (categories.size() > 0) { // 有类别                                   
        categories.forEach(category -> System.out.println(category));     
    } else { // 没有用户                                                      
        System.out.println("类别表里没有记录~");                                  
    }                                                                     
}                                                                         
③编写 测试查询全部类别
@Test // 测试插入类别                                                                 
public void testInsert() {                                            
    // 定义类别对象                                                         
    Category category = new Category();                               
    // 设置类别对象属性                                                       
    category.setName("厨房用具");                                         
    // 创建类别数据访问接口对象                                                   
    CategoryDao categoryDao = new CategoryDaoImpl();                  
    // 调用类别数据访问接口对象的插入类别方法                                            
    int count = categoryDao.insert(category);                         
    // 判断类别是否插入成功                                                     
    if (count > 0) { // 成功                                            
        System.out.println("恭喜,类别插入成功~");                             
    } else { // 失败                                                    
        System.out.println("遗憾,类别插入失败~");                             
    }                                                                 
}                                                                     

④编写测试更新类别方法
@Test // 测试更新类别                                         
public void testUpdate() {                              
    // 定义类别对象                                           
    Category category = new Category();                 
    // 设置类别对象属性                                         
    category.setId(5);                                  
    category.setName("健身器械");                           
    // 创建类别数据访问接口对象                                     
    CategoryDao categoryDao = new CategoryDaoImpl();    
    // 调用类别数据访问接口对象的更新类别方法                              
    int count = categoryDao.update(category);           
    // 判断类别是否更新成功                                       
    if (count > 0) {                                    
        System.out.println("恭喜,类别更新成功~");               
    } else {                                            
        System.out.println("遗憾,类别更新失败~");               
    }                                                   
}                                                       

⑤编写测试删除类别方法
@Test // 测试按标识符删除类别                                   
public void testDeleteById() {                        
    // 定义标识符变量                                        
    int id = 5;                                       
    // 创建类别数据访问接口对象                                   
    CategoryDao categoryDao = new CategoryDaoImpl();  
    // 调用类别数据访问接口对象的按标识符删除类别方法                        
    int count = categoryDao.deleteById(id);           
    // 判断类别是否删除成功                                     
    if (count > 0) {                                  
        System.out.println("恭喜,类别删除成功~");             
    } else {                                          
        System.out.println("遗憾,类别删除失败~");             
    }                                                 
}                                                     

5、编写商品数据访问接口实现类

  • net.xyx.shop.dao.impl包里创建ProductDaoImpl
    在这里插入图片描述
  • 实现ProductDaoImpl接口
①编写插入商品方法
@Override
    public int insert(Product product) {
        int count = 0;

        // 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "INSERT INTO t_product (name,price,add_time, category_id) VALUES (?,?,?,?)";
        try {
            //创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setString(1,product.getName());
            pstmt.setDouble(2,product.getPrice());
            pstmt.setTimestamp(3,new Timestamp(product.getAddTime().getTime()));
            pstmt.setInt(4,product.getCategotyId());
            //执行更新操作,返回插入记录数
            count = pstmt.executeUpdate();
            //关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);
        }


        return count;
    }
②编写按标识符删除商品方法
@Override//按标识符删除商品
    public int deleteById(int id) {
        //定义删除记录数
        int count = 0;

        // 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "DELETE FROM t_product WHERE id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setInt(1, id);
            // 执行更新操作,删除记录
            count = pstmt.executeUpdate();
            // 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn); // 关闭数据库连接
        }

        //返回删除记录数
        return count;
    }
③编写按标识符更新商品方法
@Override
    public int update(Product product) {
            // 定义更新记录数
            int count = 0;

            // 获得数据库连接
            Connection conn = ConnectionManager.getConnection();
            // 定义SQL字符串
            String strSQL = "UPDATE t_product SET name = ?,price = !,add_time = ?, category_id = ? WHERE id = ?";
            try {
                // 创建预备语句对象
                PreparedStatement pstmt = conn.prepareStatement(strSQL);
                // 设置占位符的值
                pstmt.setString(1, product.getName());
                pstmt.setDouble(2, product.getPrice());
                pstmt.setTimestamp(3,new Timestamp(product.getAddTime().getTime()));
                pstmt.setInt(4, product.getCategotyId());
                pstmt.setInt(5,product.getId());
                // 执行更新操作,更新记录
                count = pstmt.executeUpdate();
                // 关闭预备语句对象
                pstmt.close();
            } catch (SQLException e) {
                System.err.println(e.getMessage());
            } finally {
                ConnectionManager.closeConnection(conn); // 关闭数据库连接
            }

            // 返回更新记录数
            return count;
    }
④编写按标识符查询商品方法
@Override
    public Product findById(int id) {
        // 声明类别
        Product product = null;

        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_product WHERE id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setInt(1, id);
            // 执行SQL查询,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 判断结果集是否有记录
            if (rs.next()) {
                // 实例化商品
                product = new Product();
                // 利用当前记录字段值去设置商品类别的属性
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("privce"));
                product.setAddTime(rs.getTimestamp("add_time"));
                product.setCategotyId(rs.getInt("category_id"));
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn); // 关闭数据库连接
        }

        // 返回类别
        return product;
    }
⑤编写按类别标识符查询商品方法
@Override//按类别标识符查询商品
    public List<Product> findByCategoryId(int categoryId) {
        //定义商品列表
        List<Product> products = new ArrayList<>();

        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_product WHERE category_id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //设置占位符的值
            pstmt.setInt(1,categoryId);
            // 执行SQL查询,返回结果集
            ResultSet rs = pstmt.executeQuery();
            //遍历结果集
            while (rs.next()){
                // 实例化商品
                Product product = new Product();
                // 利用当前记录字段值去设置商品类别的属性
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("privce"));
                product.setAddTime(rs.getTimestamp("add_time"));
                product.setCategotyId(rs.getInt("category_id"));
                //将商品对象添加到商品列表
                products.add(product);
            }
            //关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        //返回商品列表
        return products;
    }
⑥编写查询全部商品方法
@Override//查询全部商品方法
    public List<Product> findAll() {
        // 声明类别列表
        List<Product> products = new ArrayList<>();

        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_category";
        try {
            // 创建语句对象
            Statement stmt = conn.createStatement();
            // 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 遍历结果集
            while (rs.next()) {
                // 创建商品实体
                Product product = new Product();
                // 设置实体属性
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                product.setAddTime(rs.getTimestamp("add_time"));
                product.setCategotyId(rs.getInt("category_id"));
                // 将实体添加到类别列表
                products.add(product);
            }
            // 关闭结果集
            rs.close();
            // 关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn); // 关闭数据库连接
        }

        // 返回类别列表
        return products;
    }

6、编写测试商品数据访问接口实现类

  • 创建测试类TestProductDaoImpl,编写测试方法testFindByCategoryId()
①编写按标识符查询商品方法
@Test
    public void testFindById(){
        int id = 1;
        ProductDao productDao = new ProductDaoImpl();
        //调用商品数据访问接口对象的按标识符查询商品方法
        Product product = productDao.findById(id);
        //判断是否找到商品
        if (product != null){
            System.out.println(product);
        }else{
            System.out.println("编号为【" + id + "】的商品未找到~");
        }
    }
  • 运行testFindById()方法,查看结果
    在这里插入图片描述
  • 修改标识符变量值,再运行
②编写测试按类别标识符查询商品方法
@Test//按类比标识符查询商品
    public void testFindByCategoryId(){
        //定义类别标识符变量
        int categoryId = 2;
        //创建商品数据访问接口对象
        ProductDao productDao = new ProductDaoImpl();
        //调用商品数据访问接口对象的按类别标识符查询商品方法
        List<Product> products = productDao.findByCategoryId(categoryId);
        //判断指定类别里是否有商品
        if (products.size() > 0){
            products.forEach(product -> System.out.println(product));
        }else{
            System.out.println("类别编号为[" + categoryId + "]的商品未找到~");
        }
    }
  • 运行testFindByCategoryId()查看结果
    在这里插入图片描述
③编写测试查询全部商品方法
@Test//测试查询全部商品
    public void testFindAll(){
        //创建类别数据访问接口对象
        ProductDao productDao = new ProductDaoImpl();
        //调用类别数据访问接口对象的按标识符查询类别方法
        List<Product>products = productDao.findAll();
        if (products.size() >0){
            products.forEach(product -> System.out.println(product));
        }else{
            System.out.println("商品表里没有记录~");
        }
    }
  • 运行testFindAll() 方法,查看结果
    在这里插入图片描述
④编写测试插入商品方法
@Test//测试插入商品
    public void testInsert(){
        //创建商品对象
        Product product = new Product();
        //设置商品对象属性
        product.setName("晨光签字笔");
        product.setPrice(3.0);
        product.setAddTime(new Date());
        product.setCategotyId(3);
        //创建类别数据访问接口对象
        ProductDao productDao = new ProductDaoImpl();
        //调用类别数据访问接口对象的插入商品方法
        int count = productDao.insert(product);
        //判断商品是否插入成功
        if (count > 0){
            System.out.println("恭喜,商品插入成功~");
        }else{
            System.out.println("抱歉,商品插入失败~");
        }
    }
  • 运行testInsert()方法,查看结果
    在这里插入图片描述

  • 在Navicat里面去查看
    在这里插入图片描述

⑤编写测试更新商品
 @Test//测试更新商品
    public  void testUpdate(){
        //定义类别对象
        Product product = new Product();
        //设置类别对象属性
        product.setId(5);
        product.setName("萌萌哒薯片");
        product.setPrice(10.0);
        product.setAddTime(new Date());
        product.setCategotyId(4);
        //创建类别数据访问接口对象
        ProductDao productDao = new ProductDaoImpl();
        //调用类别数据访问接口对象的更新类别方法
        int count = productDao.update(product);
        if(count>0){
            System.out.println("恭喜,商品更新成功~");
        }else{
            System.out.println("遗憾,商品更新失败~");
        }
    }
⑥编写测试删除商品方法
@Test//测试删除商品
    public void testDeleteById(){
        int id = 20;
        ProductDao productDao = new ProductDaoImpl();
        int count = productDao.deleteById(id);
        if(count>0){
            System.out.println("恭喜,商品删除成功~");
        }else{
            System.out.println("遗憾,商品删除失败~");
        }
    }
  • 查看运行结果
    在这里插入图片描述

7、创建订单数据访问接口类OrderDaoImpl

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值