兴科cms网站建设系统推广app赚钱项目
文章目录
- 一、创建数据库和表
- 1、创建数据库
- 2、创建用户表
- 3、创建类别表
- 4、创建商品表
- 5、创建订单表
- 二、创建Simonshop项目
- 1、创建web项目
- 2、修改Artifacts名称:simonshop
- 3、重新部署项目
- 4、编辑首页
- 5、启动应用,查看效果
- 三、创建实体类
- 1、用户实体类
- 2、创建类别实体类
- 3、创建商品实体类
- 三、创建数据库工具类
- 1、添加数据库驱动程序包
- 2、创建数据库连接管理类
- 3、测试数据库连接是否成功
- 4、数据库连接的常见错误
- (1)、数据库驱动程序名称写错误
- (2)、数据库没找到
- 5、创建数据访问接口
- (1)、创建用户数据访问接口
- (2)、类别数据访问接口CaregoryDao
- (3)、创建商品数据访问接口ProductDao
- (4)、订单数据访问接口OrderDao
- 6、数据访问接口实现类DaoImpl
- (1)、创建用户数据访问接口实现类
- ① 编写插入用户方法
- ②边界删除用户方法
- ③编写更新用户方法
- ④编写按标识符查询用户方法
- ⑤编写按用户名查询用户的方法
- ⑥编写查询全部用户方法
- ⑦编写登录方法
- (2)、对用户数据访问接口实现类做单元测试
- ①编写测试登录方法
- ②编写按标识符查询用户方法
- ③编写按用户名查询用户方法
- ④编写查询全部用户方法
- ⑤编写测试插入用户方法
- ⑥编写测试更新用户方法
- ⑦编写测试删除用户方法
- (3)、创建类别数据访问接口实现类
- ①编写插入类别方法
- ②编写按标识符插入类别方法
- ③编写更新类别方法
- ④编写按标识符查询方法
- ⑤编写查询全部方法
- (4)、 对类别数据访问接口对象做单元测试
- ①编写测试按标识符查询类别方法
- ②编写测试查询全部类别方法
- ③编写 测试查询全部类别
- ④编写测试更新类别方法
- ⑤编写测试删除类别方法
- 5、编写商品数据访问接口实现类
- ①编写插入商品方法
- ②编写按标识符删除商品方法
- ③编写按标识符更新商品方法
- ④编写按标识符查询商品方法
- ⑤编写按类别标识符查询商品方法
- ⑥编写查询全部商品方法
- 6、编写测试商品数据访问接口实现类
- ①编写按标识符查询商品方法
- ②编写测试按类别标识符查询商品方法
- ③编写测试查询全部商品方法
- ④编写测试插入商品方法
- ⑤编写测试更新商品
- ⑥编写测试删除商品方法
- 7、创建订单数据访问接口类OrderDaoImpl
一、创建数据库和表
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: HWDate: 2023/5/29Time: 15:38To 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、启动应用,查看效果
三、创建实体类
- 创建四个实体类:
User
、Category
、Product
与Order
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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic String toString() {return "Product{" +"id=" + id +", name='" + name + '\'' +", price=" + price +", addTime=" + addTime +", categotyId=" + categotyId +'}';}
}``
## 4、创建订单实体类
- 创建`ner.xyx.shop.bean`包,在包里创建订单实体类 - `Order`

- 代码如下
```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;}@Overridepublic 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 {@Testpublic 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
接口
①编写插入商品方法
@Overridepublic 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;}
③编写按标识符更新商品方法
@Overridepublic 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;}
④编写按标识符查询商品方法
@Overridepublic 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()
①编写按标识符查询商品方法
@Testpublic 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("遗憾,商品删除失败~");}}
- 查看运行结果