文章目录
- 一、创建数据库和表
-
- 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、创建类别表
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、编辑首页
<%@ 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、启动应用,查看效果
三、创建实体类
- 创建四个实体类:
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;
}
@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 {
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 {
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 {
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 {
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 {
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 {
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 {
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()
方法,查看结果
- 修改待查用户名,在运行测试方法,查看结果
④编写查询全部用户方法
@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("遗憾,更新用户失败~");
}
}
⑦编写测试删除用户方法
@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();
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();
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();
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();
String strSQL = "SELECT * FROM t_category WHERE id = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(strSQL);
pstmt.setInt(1, id);
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();
String strSQL = "SELECT * FROM t_category";
try {
Statement stmt = conn.createStatement();
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();
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();
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();
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();
String strSQL = "SELECT * FROM t_product WHERE id = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(strSQL);
pstmt.setInt(1, id);
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();
String strSQL = "SELECT * FROM t_product WHERE category_id = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(strSQL);
pstmt.setInt(1,categoryId);
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();
String strSQL = "SELECT * FROM t_category";
try {
Statement stmt = conn.createStatement();
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