Java Web学习:西蒙购物网【上】

学习Java Web做了一个购物网
一、创建实体类
在src里创建net.cl.shop.bean包,创建四个实体类:User、Category、Product与Order,与四张表t_user、t_category、t_product与t_order一一对应。
1、用户实体类User

package net.cl.shop.bean;


import java.util.Date;

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

    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 +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", telephone='" + telephone + '\'' +
                ", registerTime=" + registerTime +
                ", popedom=" + popedom +
                '}';
    }
}

2、商品类别实体类Category

package net.cl.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、商品实体类Product

package net.cl.shop.bean;

import java.util.Date;

public class Product {
    /**
     * 商品标识符
     */
    private int id;
    /**
     * 商品名称
     */
    private String name;
    /**
     * 商品单价
     */
    private double price;
    /**
     * 商品上架时间
     */
    private Date addTime;
    /**
     * 商品所属类别标识符
     */
    private int categoryId;

    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 getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

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

4、商品订单实体类Order

package net.cl.shop.bean;

import java.util.Date;

public class Order {
    /**
     * 订单标识符
     */
    private int id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 联系电话
     */
    private String telephone;
    /**
     * 订单总金额
     */
    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 getTelephone() {
        return telephone;
    }

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

    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 + '\'' +
                ", telephone='" + telephone + '\'' +
                ", totalPrice=" + totalPrice +
                ", deliveryAddress='" + deliveryAddress + '\'' +
                ", orderTime=" + orderTime +
                '}';
    }
}

二、创建数据库工具类ConnectionManager
1、在web\WEB-INF目录下创建lib子目录,添加MySQL驱动程序的jar包
在这里插入图片描述
2、在src下创建net.hw.shop.dbutil包,在里面创建ConnectionManager类
在这里插入图片描述

package net.cl.shop.dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JOptionPane;

public class ConnectionManager {
    /**
     * 数据库驱动程序
     */
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    /**
     * 数据库统一资源标识符
     */
    private static final String URL = "jdbc:mysql://localhost:3306/simonshop";
    /**
     * 数据库用户名
     */
    private static final String USERNAME = "root";
    /**
     * 数据库密码
     */
    private static final String PASSWORD = "1";

    /**
     * 私有化构造方法,拒绝实例化
     */
    private ConnectionManager() {
    }

    /**
     * 获得数据库连接
     *
     * @return 数据库连接对象
     */
    public static Connection getConnection() {
        // 定义数据库连接
        Connection conn = null;
        try {
            // 安装数据库驱动程序
            Class.forName(DRIVER);
            // 获得数据库连接
            conn = DriverManager.getConnection(URL
                    + "?useUnicode=true&characterEncoding=UTF8", USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 返回数据库连接
        return conn;
    }

    /**
     * 关闭数据库连接
     *
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        // 判断数据库连接是否为空
        if (conn != null) {
            // 判断数据库连接是否关闭
            try {
                if (!conn.isClosed()) {
                    // 关闭数据库连接
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试数据库连接是否成功
     *
     * @param args
     */
    public static void main(String[] args) {
        // 获得数据库连接
        Connection conn = getConnection();
        // 判断是否连接成功
        if (conn != null) {
            JOptionPane.showMessageDialog(null, "恭喜,数据库连接成功!");
        } else {
            JOptionPane.showMessageDialog(null, "遗憾,数据库连接失败!");
        }

        // 关闭数据库连接
        closeConnection(conn);
    }
}

运行并查看结果:
在这里插入图片描述
三、数据访问接口
在src里创建net.clshop.dao包,在里面创建UserDao、CategoryDao、ProductDao与OrderDao。
1、用户数据访问接口UserDao

package net.cl.shop.dao;


import java.util.List;

import net.cl.shop.bean.User;

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、类别数据访问接口CategoryDao

package net.cl.shop.dao;

/**
 * 功能:类别数据访问接口
 * 作者:华卫
 * 日期:2019年12月10日
 */
import java.util.List;

import net.cl.shop.bean.Category;

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

3、商品数据访问接口ProductDao

package net.cl.shop.dao;

import java.util.List;

import net.cl.shop.bean.Product;

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

package net.cl.shop.dao;

import java.util.List;

import net.cl.shop.bean.Order;

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

四、数据访问接口实现类
在src下创建net.cl.shop.dao.impl包,在里面创建UserDaoImpl、CategoryDaoImpl、ProductDaoImpl与OrderDaoImpl。
1用户数据访问接口实现类UserDaoImpl

package net.cl.shop.dao.impl;


import net.cl.shop.bean.User;
import net.cl.shop.dao.UserDao;
import net.cl.shop.dbutil.ConnectionManager;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    /**
     * 插入用户
     */
    @Override
    public int insert(User user) {
        // 定义插入记录数
        int count = 0;

        // 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "INSERT INTO t_user (username, password, telephone, register_time, popedom)"
                + " VALUES (?, ?, ?, ?, ?)";
        try {
            // 创建预备语句对象
            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 e) {
            e.printStackTrace();
        } 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_user WHERE id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setInt(1, id);
            // 执行更新操作,删除记录
            count = pstmt.executeUpdate();
            // 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        // 返回删除记录数
        return count;
    }

    /**
     * 更新用户
     */
    @Override
    public int update(User user) {
        // 定义更新记录数
        int count = 0;

        // 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "UPDATE t_user SET username = ?, password = ?, telephone = ?,"
                + " register_time = ?, popedom = ? WHERE id = ?";
        try {
            // 创建预备语句对象
            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) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        // 返回更新记录数
        return count;
    }

    /**
     * 按标识符查询用户
     */
    @Override
    public User findById(int id) {
        // 声明用户
        User user = null;

        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_user WHERE id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setInt(1, id);
            // 执行SQL查询,返回结果集
            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"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        // 返回用户
        return user;
    }

    @Override
    public List<User> findByUsername(String username) {
        // 声明用户列表
        List<User> users = new ArrayList<User>();
        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_user WHERE username = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setString(1, username);
            // 执行SQL查询,返回结果集
            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);
            }
            // 关闭结果集
            rs.close();
            // 关闭语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回用户列表
        return users;
    }

    @Override
    public List<User> findAll() {
        // 声明用户列表
        List<User> users = new ArrayList<User>();
        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_user";
        try {
            // 创建语句对象
            Statement stmt = conn.createStatement();
            // 执行SQL,返回结果集
            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);
            }
            // 关闭结果集
            rs.close();
            // 关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回用户列表
        return users;
    }

    /**
     * 登录方法
     */
    @Override
    public User login(String username, String password) {
        // 定义用户对象
        User user = null;
        // 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_user WHERE username = ? AND password = ?";
        try {
            // 创建预备语句对象
            PreparedStatement psmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            psmt.setString(1, username);
            psmt.setString(2, password);
            // 执行查询,返回结果集
            ResultSet rs = psmt.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.getDate("register_time"));
                user.setPopedom(rs.getInt("popedom"));
            }
            // 关闭结果集
            rs.close();
            // 关闭预备语句
            psmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回用户对象
        return user;
    }
}

对用户数据接口访问实现类的各个方法进行单元测试,采用JUnit进行单元测试
在项目根目录创建一个test文件夹,然后在项目结构窗口里将其标记为"Test",这样文件夹颜色变成绿色。

在这里插入图片描述
在test文件夹里创建net.cl.shop.dao.impl包,在里面创建测试类TestUserDaoImpl:

1、编写测试用户插入testinsert()
在这里插入图片描述
/**
* 用户插入
/
@Test
public void testinsert(){
UserDao userDao = new UserDaoImpl();
User user = new User();
user.setUsername(“郭靖”);
user.setPassword(“admin”);
user.setTelephone(“15679486591”);
user.setRegisterTime(new Date());
int count = userDao.insert(user);
if (count > 0){
System.out.println(“用户插入成功!”);
System.out.println(userDao.findById(userDao.findAll().size()));
}else {
System.out.println(“用户插入失败!”);
}
}
2、编写测试用户更新 txtUpdate()
在这里插入图片描述
/
* 更新用户
/
@Test
public void txtUpdate(){
UserDao userDao = new UserDaoImpl();
User user = userDao.findById(4);
user.setPassword(“903223”);
user.setTelephone(“15346785973”);
int count = userDao.update(user);
if (count > 0){
System.out.println(“用户更新成功”);
}else {
System.out.println(“用户更新失败”);
}
user = userDao.findById(4);
System.out.println(user);
}

3、编写测试删除用户 testdeleteById()
在这里插入图片描述
将查询的id改为17,再一次查询:显示删除失败
在这里插入图片描述
/
* 删除用户记录
/
@Test
public void testdeleteById(){
UserDao userDao = new UserDaoImpl();
int count = userDao.deleteById(7);
if (count > 0){
System.out.println(“用户删除成功!”);
}else {
System.out.println(“用户删除失败!”);
System.out.println("[" + count + “]不存在,请重新输入!”);
}
}
*
4、编写测试用户登录testLogin()
在这里插入图片描述
将username修改为杨过在测试,结果为:登录失败
在这里插入图片描述
/
* 用户登录
/
@Test
public void testLogin() {
String username, password;
username = “admin”;
password = “12345”;
// 父接口指向子类对象
UserDao userDao = new UserDaoImpl();
User user = userDao.login(username, password);
// 判断用户登录是否成功
if (user != null) {
System.out.println(“恭喜,登录成功!”);
} else {
System.out.println(“遗憾,登录失败!”);
}
}
*
5、编写测试查找所有用户 testFindAll()在这里插入图片描述

/**
 * 查找所有用户
 */
@Test
public void testFindAll(){
    UserDao userDao = new UserDaoImpl();
    List<User> userList = userDao.findAll();
    if (userList.size() > 0){
        for (User user:userList) {
            System.out.println(user);
        }
    }else {
        System.out.println("没有用户!");
    }
}

6、编写测试按id查询用户 testfindById()
在这里插入图片描述
将id修改为15,再一次测试,结果为:显示无此id
在这里插入图片描述
/
* 按id查询
/
@Test
public void testfindById(){
UserDao userDao = new UserDaoImpl();
User user = userDao.findById(1);
System.out.println(user);
}
*
7、编写测试按username查询testfindByUsername()
在这里插入图片描述
将username修改为杨过,在测试,结果为:空值
在这里插入图片描述
/**
* 按用户名查询
*/
@Test
public void testfindByUsername(){
String username;
username = “admin”;
UserDao userDao = new UserDaoImpl();
List user = userDao.findByUsername(username);
if (user != null){
System.out.println(user);
}else {
System.out.println(user + “不存在!”);
}

}

2、类别数据接口实现类CategoryDaoImpl

package net.cl.shop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import net.cl.shop.bean.Category;
import net.cl.shop.dao.CategoryDao;
import net.cl.shop.dbutil.ConnectionManager;

public class CategoryDaoImpl implements CategoryDao {
    /**
     * 插入类别
     */
    @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) {
            e.printStackTrace();
        } 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) {
            e.printStackTrace();
        } 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) {
            e.printStackTrace();
        } 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) {
            e.printStackTrace();
        } 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) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回类别列表
        return categories;
    }
}

创建测试类TestCategoryDaoImpl,编写测试方法testFindAll():
在这里插入图片描述
查询失败的为:
在这里插入图片描述

    /**
     * 查询所有商品
     */
    @Test
    public void testFindAll(){
        CategoryDao categoryDao = new CategoryDaoImpl();
        List<Category> categories = categoryDao.findAll();
        if (categories.size() > 0){
            for (Category category:categories){
                System.out.println(categories);
            }
        }else {
            System.out.println("没有商品类别!");
        }
    }

2、编写测试类testinsert()
在这里插入图片描述
失败的为:
在这里插入图片描述
3、编写测试类testdeleteById()
在这里插入图片描述
将查询id修改为5,再一次测试结果为:删除失败
在这里插入图片描述
4、编写测试类txtUpdate()
在这里插入图片描述
5、编写测试类testfindById()
在这里插入图片描述
将id修改为20.测试结果为:没有此商品
在这里插入图片描述
3、商品数据访问接口类ProductDaoImpl

package net.cl.shop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import net.cl.shop.bean.Product;
import net.cl.shop.dao.ProductDao;
import net.cl.shop.dbutil.ConnectionManager;

class ProductDaoImpl implements ProductDao {
    /**
     * 插入商品
     */
    @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.getCategoryId());
            // 执行更新操作,插入新记录
            count = pstmt.executeUpdate();
            // 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } 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) {
            e.printStackTrace();
        } 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.getCategoryId());
            pstmt.setInt(5, product.getId());
            // 执行更新操作,更新记录
            count = pstmt.executeUpdate();
            // 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } 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("price"));
                product.setAddTime(rs.getTimestamp("add_time"));
                product.setCategoryId(rs.getInt("category_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        // 返回商品
        return product;
    }

    /**
     * 按类别查询商品
     */
    @Override
    public List<Product> findByCategoryId(int categoryId) {
        // 定义商品列表
        List<Product> products = new ArrayList<Product>();

        // 获取数据库连接
        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("price"));
                product.setAddTime(rs.getTimestamp("add_time"));
                product.setCategoryId(rs.getInt("category_id"));
                // 将商品添加到商品列表
                products.add(product);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }
        // 返回商品列表
        return products;
    }

    /**
     * 查询全部商品
     */
    @Override
    public List<Product> findAll() {
        // 声明商品列表
        List<Product> products = new ArrayList<Product>();
        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_product";
        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.setCategoryId(rs.getInt("category_id"));
                // 将实体添加到商品列表
                products.add(product);
            }
            // 关闭结果集
            rs.close();
            // 关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回商品列表
        return products;
    }
}

创建测试类TestProductDaoImpl,编写测试方法testinsert()并测试
在这里插入图片描述
在说一个不成功的:
在这里插入图片描述
2、编写测试类testdeleteById()
在这里插入图片描述
将id修改为17,测试结果为:删除失败
在这里插入图片描述
3、编写测试类txtUpdate()
在这里插入图片描述
失败的是:
在这里插入图片描述
4、编写测试类testfindById()
在这里插入图片描述
5、编写测试类testFindAll()
在这里插入图片描述
4、订单数据访问接口实现类OrderDaoImpl

package net.cl.shop.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import net.cl.shop.bean.Order;
import net.cl.shop.dao.OrderDao;
import net.cl.shop.dbutil.ConnectionManager;

public class OrderDaoImpl implements OrderDao {
    /**
     * 插入订单
     */
    @Override
    public int insert(Order order) {
        // 定义插入记录数
        int count = 0;

        // 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "INSERT INTO t_order (username, telephone, total_price, delivery_address, order_time)"
                + " VALUES (?, ?, ?, ?, ?)";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setString(1, order.getUsername());
            pstmt.setString(2, order.getTelephone());
            pstmt.setDouble(3, order.getTotalPrice());
            pstmt.setString(4, order.getDeliveryAddress());
            pstmt.setTimestamp(5, new Timestamp(order.getOrderTime().getTime()));
            // 执行更新操作,插入记录
            count = pstmt.executeUpdate();
            // 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } 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_order WHERE id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setInt(1, id);
            // 执行更新操作,删除记录
            count = pstmt.executeUpdate();
            // 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        // 返回删除记录数
        return count;
    }

    /**
     * 更新订单
     */
    @Override
    public int update(Order order) {
        // 定义更新记录数
        int count = 0;

        // 获得数据库连接
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "UPDATE t_order SET username = ?, telephone = ?, total_price = ?,"
                + " delivery_address = ?, order_time = ? WHERE id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setString(1, order.getUsername());
            pstmt.setString(2, order.getTelephone());
            pstmt.setDouble(3, order.getTotalPrice());
            pstmt.setString(4, order.getDeliveryAddress());
            pstmt.setTimestamp(5, new Timestamp(order.getOrderTime().getTime()));
            pstmt.setInt(6, order.getId());
            // 执行更新操作,更新记录
            count = pstmt.executeUpdate();
            // 关闭预备语句对象
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        // 返回更新记录数
        return count;
    }

    /**
     * 查询最后一个订单
     */
    @Override
    public Order findLast() {
        // 声明订单
        Order order = null;
        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_order";
        try {
            // 创建语句对象
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            // 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 定位到最后一条记录
            if (rs.last()) {
                // 创建订单实体
                order = new Order();
                // 设置实体属性
                order.setId(rs.getInt("id"));
                order.setUsername(rs.getString("username"));
                order.setTelephone(rs.getString("telephone"));
                order.setTotalPrice(rs.getDouble("total_price"));
                order.setDeliveryAddress(rs.getString("delivery_address"));
                order.setOrderTime(rs.getTimestamp("order_time"));
            }
            // 关闭结果集
            rs.close();
            // 关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回订单对象
        return order;
    }

    /**
     * 按标识符查询订单
     */
    @Override
    public Order findById(int id) {
        // 声明订单
        Order order = null;

        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_order WHERE id = ?";
        try {
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符的值
            pstmt.setInt(1, id);
            // 执行SQL查询,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 判断结果集是否有记录
            if (rs.next()) {
                // 实例化订单
                order = new Order();
                // 利用当前记录字段值去设置订单的属性
                order.setId(rs.getInt("id"));
                order.setUsername(rs.getString("username"));
                order.setTelephone(rs.getString("telephone"));
                order.setDeliveryAddress(rs.getString("delivery_address"));
                order.setOrderTime(rs.getTimestamp("order_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            ConnectionManager.closeConnection(conn);
        }

        // 返回订单
        return order;
    }

    /**
     * 查询全部订单
     */
    @Override
    public List<Order> findAll() {
        // 声明订单列表
        List<Order> orders = new ArrayList<Order>();
        // 获取数据库连接对象
        Connection conn = ConnectionManager.getConnection();
        // 定义SQL字符串
        String strSQL = "SELECT * FROM t_order";
        try {
            // 创建语句对象
            Statement stmt = conn.createStatement();
            // 执行SQL,返回结果集
            ResultSet rs = stmt.executeQuery(strSQL);
            // 遍历结果集
            while (rs.next()) {
                // 创建订单实体
                Order order = new Order();
                // 设置实体属性
                order.setId(rs.getInt("id"));
                order.setUsername(rs.getString("username"));
                order.setTelephone(rs.getString("telephone"));
                order.setDeliveryAddress(rs.getString("delivery_address"));
                order.setOrderTime(rs.getTimestamp("order_time"));
                // 将实体添加到订单列表
                orders.add(order);
            }
            // 关闭结果集
            rs.close();
            // 关闭语句对象
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }
        // 返回用户列表
        return orders;
    }
}

创建测试类TestOrderDaoImpl,编写测试方法testFinAll():
在这里插入图片描述
2、编写测试类testinsert()
在这里插入图片描述
3、白那些测试类testdeleteById()
在这里插入图片描述
4、编写测试类txtUpdate()
在这里插入图片描述
5、编写测试类testfindById()
在这里插入图片描述
6、编写测试类testfindLast()
在这里插入图片描述
7、编写测试类testFindAll()
在这里插入图片描述
TesOrderDaoImpl代码:

package net.cl.shop.dao.impl;

import net.cl.shop.bean.Order;
import net.cl.shop.dao.OrderDao;
import org.junit.Test;

import java.util.Date;
import java.util.List;

public class TestOrderDaoImpl {
    /**
     * 订单插入
     */
    @Test
    public void testinsert(){
        OrderDao orderDao = new OrderDaoImpl();
        Order order = new Order();
        order.setUsername("郭靖");
        order.setTelephone("16856234976");
        order.setTotalPrice(234);
        order.setDeliveryAddress("泸职院信息工程系");
        order.setOrderTime(new Date());
        int count = orderDao.insert(order);
        if (count > 0){
            System.out.println("订单插入成功!");
            System.out.println(orderDao.findById(orderDao.findAll().size()));
        }else {
            System.out.println("订单插入失败!");
        }
    }
    /**
     * 删除订单记录
     */
    @Test
    public void testdeleteById(){
        OrderDao orderDao = new OrderDaoImpl();
        int count = orderDao.deleteById(2);
        if (count > 0){
            System.out.println("订单删除成功!");
        }else {
            System.out.println("订单删除失败!");
        }
    }
    /**
     * 更新订单
     */
    @Test
    public void txtUpdate(){
        OrderDao orderDao = new OrderDaoImpl();
        Order order = orderDao.findById(4);
        order.setUsername("郭靖");
        order.setTotalPrice(123);
        order.setDeliveryAddress("泸职院电子工程系");
        int count = orderDao.update(order);
        if (count > 0){
            System.out.println("订单更新成功");
        }else {
            System.out.println("订单更新失败");
        }
    }
    /**
     * 按id查询
     */
    @Test
    public void testfindById(){
        OrderDao orderDao = new OrderDaoImpl();
        Order order = orderDao.findById(1);
        if (order != null) {
            System.out.println(order);
        }else {
            System.out.println("没有此ID");
        }
    }
    /**
     * 查询最后一个订单
     */
    @Test
    public void testfindLast(){
        OrderDao orderDao = new OrderDaoImpl();
        Order order = orderDao.findLast();
        if (order != null) {
            System.out.println(order);
        }else {
            System.out.println("没有此ID");
        }

    }
    /**
     * 查找所有订单
     */
    @Test
    public void testFindAll(){
        OrderDao orderDao = new OrderDaoImpl();
        List<Order> orders = orderDao.findAll();
        if (orders.size() > 0){
            for (Order order:orders){
                System.out.println(order);
            }
        }else {
            System.out.println("没有订单!");
        }
    }

}

五、数据访问服务类
一、在src里创建netcl.shop.service包,在里面创建四个服务类:UserService、CategoryService、ProductService与OrderService。
1、用户服务类UserService

package net.cl.shop.service;

import java.util.List;

import net.cl.shop.bean.User;
import net.cl.shop.dao.UserDao;
import net.cl.shop.dao.impl.UserDaoImpl;

public class UserService {
    /**
     * 声明用户访问对象
     */
    private UserDao userDao = new UserDaoImpl();

    public int addUser(User user) {
        return userDao.insert(user);
    }

    public int deleteUserById(int id) {
        return userDao.deleteById(id);
    }

    public int updateUser(User user) {
        return userDao.update(user);
    }

    public User findUserById(int id) {
        return userDao.findById(id);
    }

    public List<User> findUsersByUsername(String username) {
        return userDao.findByUsername(username);
    }

    public List<User> findAllUsers() {
        return userDao.findAll();
    }

    public User login(String username, String password) {
        return userDao.login(username, password);
    }
}

2、类别服务类CategoryServicepackage net.cl.shop.service;

import java.util.List;

import net.cl.shop.bean.Category;
import net.cl.shop.dao.CategoryDao;
import net.cl.shop.dao.impl.CategoryDaoImpl;

public class CategoryService {
/**
* 声明类别数据访问对象
*/
private CategoryDao categoryDao = new CategoryDaoImpl();

public int addCategory(Category category) {
    return categoryDao.insert(category);
}

public int deleteCategoryById(int id) {
    return categoryDao.deleteById(id);
}

public int updateCategory(Category category) {
    return categoryDao.update(category);
}

public Category findCategoryById(int id) {
    return categoryDao.findById(id);
}

public List<Category> findAllCategories() {
    return categoryDao.findAll();
 }
}

3、商品服务类ProductService

package net.cl.shop.service;

import java.util.List;

import net.cl.shop.bean.Product;
import net.cl.shop.dao.ProductDao;
import net.cl.shop.dao.impl.ProductDaoImpl;

public class ProductService {
    /**
     * 声明商品数据访问对象
     */
    private ProductDao productDao = new ProductDaoImpl();

    public int addProduct(Product product) {
        return productDao.insert(product);
    }

    public int deleteProductById(int id) {
        return productDao.deleteById(id);
    }

    public int updateProduct(Product product) {
        return productDao.update(product);
    }

    public Product findProductById(int id) {
        return productDao.findById(id);
    }

    public List<Product> findProductsByCategoryId(int categoryId) {
        return productDao.findByCategoryId(categoryId);
    }

    public List<Product> findAllProducts() {
        return productDao.findAll();
    }
}

4、订单服务类OrderService

package net.cl.shop.service;

import java.util.List;

import net.cl.shop.bean.Order;
import net.cl.shop.dao.OrderDao;
import net.cl.shop.dao.impl.OrderDaoImpl;

public class OrderService {
    /**
     * 声明订单数据访问对象
     */
    OrderDao orderDao = new OrderDaoImpl();

    public int addOrder(Order order) {
        return orderDao.insert(order);
    }

    public int deleteOrderById(int id) {
        return orderDao.deleteById(id);
    }

    public int updateOrder(Order order) {
        return orderDao.update(order);
    }

    public Order findOrderById(int id) {
        return orderDao.findById(id);
    }

    public Order findLastOrder() {
        return orderDao.findLast();
    }

    public List<Order> findAllOrders() {
        return orderDao.findAll();
    }
}


二、创建四个测试类TestUserService、TestCategoryService、TestProductService与TestOrderService,编写测试方法测试四个服务类里的各个方法
创建TestUserServiceImpl,编写测试类testaddUser()
在这里插入图片描述

package net.cl.shop.service;

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

import java.util.Date;
import java.util.List;

public class TestUserService {
    @Test
    public void testaddUser(){
        UserService userService = new UserService();
        User user = new User();
        user.setPassword("admin");
        user.setTelephone("15679486591");
        user.setRegisterTime(new Date());
        int count = userService.addUser(user);
        if (count > 0){
            System.out.println("用户插入成功!");
        }else {
            System.out.println("用户插入失败!");
        }
    }
    @Test
    public void testdeleteUserById(){
        UserService userService = new UserService();
        int count = userService.deleteUserById(7);
        if (count > 0){
            System.out.println("用户删除成功!");
        }else {
            System.out.println("用户删除失败!");
        }
    }
    @Test
    public void testupdateUser(){
        UserService userService = new UserService();
        User user = userService.findUserById(1);
        user.setPassword("903223");
        user.setTelephone("15346785973");
        int count = userService.updateUser(user);
        if (count > 0){
            System.out.println("用户更新成功");
        }else {
            System.out.println("用户更新失败");
        }
    }
    @Test
    public void testfindUserById(){
        UserService userService = new UserService();
        User user = userService.findUserById(15);
        if (user != null){
            System.out.println(user);
        }else {
            System.out.println("没有此id");
        }
    }
    @Test
    public void testfindUsersByUsername(){
        String username;
        username = "郭靖";
        UserService userService = new UserService();
        List<User> user = userService.findUsersByUsername(username);
        if (user != null){
            System.out.println(user);
        }else {
            System.out.println("没有此用户名");
        }
    }
    @Test
    public void testfindAllUsers(){
        UserService userService =  new UserService();
        List<User> userList = userService.findAllUsers();
        if (userList.size() > 0){
            for (User user:userList) {
                System.out.println(user);
            }
        }else {
            System.out.println("没有用户!");
        }
    }
    @Test
    public void testlogin(){
        String username,password;
        username = "admin";
        password = "admin";
        UserService userService = new UserService();
        User user= userService.login(username,password);
        if (user != null) {
            System.out.println("恭喜,登录成功!");
        } else {
            System.out.println("遗憾,登录失败!");
        }
    }
}

1、编写测试类
2、编写测试类testdeleteUserById()
在这里插入图片描述
3、编写测试类testupdateUser()
在这里插入图片描述
4、编写测试类testfindUserById()
在这里插入图片描述
5、编写测试类testfindUsersByUsername()
在这里插入图片描述
6、编写测试类testfindAllUsers()
在这里插入图片描述
7、编写测试类testlogin()
在这里插入图片描述
创建TestCategoryservice
在这里插入图片描述

package net.cl.shop.service;

import net.cl.shop.bean.Category;
import net.cl.shop.bean.Product;
import org.junit.Test;

import java.util.List;

public class TestCategoryService {
    @Test
    public void testaddCategory(){
        CategoryService categoryService = new CategoryService();
        Category category = new Category();
        category.setName("运动用品");
        category.setId(5);
        int count = categoryService.addCategory(category);
        if (count > 0){
            System.out.println("商品插入成功!");
        }else {
            System.out.println("商品插入失败!");
        }
    }
    @Test
    public void testdeleteCategoryById(){
        CategoryService categoryService = new CategoryService();
        int count = categoryService.deleteCategoryById(4);
        if (count > 0){
            System.out.println("商品删除成功!");
        }else {
            System.out.println("商品删除失败!");
        }
    }
    @Test
    public void testupdateCategory(){
        CategoryService categoryService = new CategoryService();
        Category category = categoryService.findCategoryById(2);
        category.setName("运动用品");
        int count = categoryService.updateCategory(category);
        if (count > 0){
            System.out.println("商品更新成功");
        }else {
            System.out.println("商品更新失败");
        }
    }
    @Test
    public void testfindCategoryById(){
        CategoryService categoryService = new CategoryService();
        Category category = categoryService.findCategoryById(20);
        if (category != null){
            System.out.println(category);
        }else {
            System.out.println("没有此商品");
        }
    }
    @Test
    public void testfindAllCategories(){
        CategoryService categoryService = new CategoryService();
        List<Category> categories = categoryService.findAllCategories();
        if (categories.size() > 0){
            for (Category category:categories){
                System.out.println(categories);
            }
        }else {
            System.out.println("没有商品类别!");
        }
    }
}

1、编写测试类testaddCategory()
在这里插入图片描述
2、编写测试类testdeleteCategoryById()
在这里插入图片描述
3、编写测试类testupdateCategory()
在这里插入图片描述
4、编写测试类testfindCategoryById()
在这里插入图片描述
5、编写测试类testfindAllCategories()
在这里插入图片描述
创建TestProductService

package net.cl.shop.service;

import net.cl.shop.bean.Product;
import org.junit.Test;

import java.util.Date;
import java.util.List;

public class TestProductService {
    @Test
    public void TestaddProduct(){
        ProductService productService = new ProductService();
        Product product = new Product();
        product.setName("毛毯");
        product.setPrice(35);
        product.setAddTime(new Date());
        product.setCategoryId(1);
        int count = productService.addProduct(product);
        if (count > 0){
            System.out.println("商品插入成功!");
        }else {
            System.out.println("商品插入失败!");
        }
    }
    @Test
    public void testdeleteProductById(){
        ProductService productService = new ProductService();
        int count = productService.deleteProductById(17);
        if (count > 0){
            System.out.println("商品删除成功!");
        }else {
            System.out.println("商品删除失败!");
        }
    }
    @Test
    public void testfindProductsByCategoryId(){
        ProductService productService = new ProductService();
        int categoryId = 1;
        if (productService.findProductById(categoryId) != null){
            String categoryName = productService.findProductById(categoryId).getName();
            List<Product> products = productService.findProductsByCategoryId(categoryId);
            if (!products.isEmpty()){
                for (Product product:products){
                    System.out.println(product);
                }
            }else {
                System.out.println("[" + categoryName + "]类别没有商品!");
            }
        }else {
            System.out.println("类别编号[" + categoryId + "]不存在!");
        }
    }
    @Test
    public void testupdateProduct(){
        ProductService productService = new ProductService();
        Product product = productService.findProductById(4);
        product.setCategoryId(2);
        product.setPrice(888);
        product.setName("羊毛毯");
        int count = productService.updateProduct(product);
        if (count > 0){
            System.out.println("商品更新成功");
        }else {
            System.out.println("商品更新失败");
        }
    }    @Test
    public void testfindProductById(){
        ProductService productService = new ProductService();
        Product product = productService.findProductById(1);
        if (product != null) {
            System.out.println(product);
        }else {
            System.out.println("没有此id");
        }
    }


}

1、编写测试类TestaddProduct()
在这里插入图片描述
2、编写测试类testdeleteProductById()
在这里插入图片描述
3、编写测试类testfindProductsByCategoryId()
在这里插入图片描述
4、编写测试类testupdateProduct()
在这里插入图片描述
5、编写测试类testfindProductById(){
在这里插入图片描述
创建TestOrderService
在这里插入图片描述
1、编写测试类testAddorder()
在这里插入图片描述
3、编写测试类testdeleteOrderById()
在这里插入图片描述
4、编写测试类TestupdateOrder()
在这里插入图片描述
5、编写测试类testfindOrderById()
在这里插入图片描述
6、编写测试类testfindLastOrder()
在这里插入图片描述
7、编写测试类testfindAllOrders()
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值