文章目录
网站实现步骤
(一)创建数据库与表
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');
```![请添加图片描述](https://img-blog.csdnimg.cn/bb094268269644eb885078885ff5d7ae.png)
### 3、创建类别表
创建类别表结构 - t_category![请添加图片描述](https://img-blog.csdnimg.cn/5da66784217e463ebbaf95c3959efbde.png)
```xml
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', '泸职院大数据学院', '2023-05-25 17:12:36');
INSERT INTO `t_order` VALUES ('2', '温志军', '13956678907', '1000', '泸职院机械工程学院', '2023-05-26 17:12:17');
(二)创建Web项目
1、创建Web项目
创建Java Enterprise项目,添加Web Application功能
2、修改Artifact名称
将Artifact名称改为simonshop
3、重新部署项目
先移除,后添加,重新部署项目
4、编辑首页
首页 - index.jsp
<%@ page import="java.util.Date" %>
<%@ 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,与四张表t_user、t_category、t_product与t_order一一对应。ORM(Object Relation Mapping)——对象关系映射。
1、创建用户实体类
创建net.huawei.shop.bean包,在包里创建User类
package net.huawei.shop.bean;
import java.util.Date;
/**
* 功能:用户实体类
* 作者:华卫
* 日期:2023年05月29日
*/
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 +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
2、创建类别实体类
在net.huawei.shop.bean包里创建Category类
package net.huawei.shop.bean;
/**
* 功能:类别实体类
* 作者:华卫
* 日期:2023年05月29日
*/
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、创建商品实体类
在net.huawei.shop.bean包里创建Product类
package net.huawei.shop.bean;
import java.util.Date;
/**
* 功能:商品实体类
* 作者:华卫
* 日期:2023年05月29日
*/
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、创建订单实体类
在net.huawei.shop.bean包里创建Order类
package net.huawei.shop.bean;
import java.util.Date;
/**
* 功能:订单实体类
* 作者:华卫
* 日期:2023年05月29日
*/
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 +
'}';
}
}
(四)创建数据库工具类
1、添加数据库驱动程序包
在\WEB-INF里创建lib子目录,添加MySQL驱动程序的jar包
2、创建数据库连接管理类
创建net.huawei.shop.dbutil包,在里面创建ConnectionManager类
package net.huawei.shop.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 功能:数据库连接管理类
* 作者:华卫
* 日期:2023年05月19日
*/
public class ConnectionManager {
private static final String DRIVER = "com.mysql.jdbc.Driver"; // 数据库驱动程序
private static final String URL = "jdbc:mysql://localhost:3306/simonshop?useSSL=false&useUnicode=true&characterEncoding=utf8"; // 数据库统一资源标识符
private static final String USER = "root"; // 数据库用户
private static final String PASSWORD = "903213"; // 数据库密码(记住改成自己的数据库密码)
// 私有化构造方法,拒绝实例化
private ConnectionManager() {
}
// 获取数据库连接静态方法
public static Connection getConnection() {
// 定义数据库连接
Connection conn = null;
try {
// 安装数据库驱动程序
Class.forName(DRIVER);
// 获取数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
System.err.println(e.getMessage());
} catch (SQLException e) {
System.err.println(e.getMessage());
}
// 返回数据库连接
return conn;
}
// 关闭数据连接静态方法
public static void closeConnection(Connection conn) {
// 判断数据库连接是否非空
if (conn != null) {
try {
// 判断连接是否未关闭
if (!conn.isClosed()) {
// 关闭数据库连接
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// 获取数据库连接
Connection conn = getConnection();
// 判断数据库连接是否成功
if (conn != null) {
System.out.println("恭喜,数据库连接成功~");
} else {
System.out.println("遗憾,数据库连接失败~");
}
// 关闭数据库连接
closeConnection(conn);
System.out.println("数据库连接已经关闭~");
}
}
3、测试数据库连接是否成功
运行程序,查看结果
4、数据库连接的常见错误
(1)数据库驱动程序名称错误
数据库驱动程序名称写错
(2)未知数据库没错误
数据库名称写错
(3)数据库连接密码错误
数据库密码写错
(五)创建数据访问接口
1、创建用户数据访问接口
在net.huawei.shop根包里创建dao子包,在子包里创建UserDao接口
package net.huawei.shop.dao;
import net.huawei.shop.bean.User;
import java.util.List;
/**
* 功能:用户数据访问接口
* 作者:华卫
* 日期:2023年05月29日
*/
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、创建类别数据访问接口
在net.huawei.shop.dao包里创建CategoryDao接口
package net.huawei.shop.dao;
import net.huawei.shop.bean.Category;
import java.util.List;
/**
* 功能:类别数据访问接口
* 作者:华卫
* 日期:2023年05月29日
*/
public interface CategoryDao {
int insert(Category category); // 插入类别
int deleteById(int id); // 按标识符删除类别
int update(Category category); // 更新类别
Category findById(int id); // 按标识符查询类别
List<Category> findAll(); // 查询全部类别
}
3、创建商品数据访问接口
在net.huawei.shop.dao包里创建ProductDao接口
package net.huawei.shop.dao;
import net.huawei.shop.bean.Product;
import java.util.List;
/**
* 功能:商品数据访问接口
* 作者:华卫
* 日期:2023年05月29日
*/
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、创建订单数据访问接口
在net.huawei.shop.dao包里创建OrderDao接口
package net.huawei.shop.dao;
import net.huawei.shop.bean.Order;
import java.util.List;
/**
* 功能:订单数据访问接口
* 作者:华卫
* 日期:2023年05月29日
*/
public interface OrderDao {
int insert(Order order); // 插入订单
int deleteById(int id); // 按标识符删除订单
int update(Order order); // 更新订单
Order findById(int id); // 按标识符查询订单
Order findLast(); // 查询最后一个订单
List<Order> findAll(); // 查询全部订单
}
(六)创建数据访问接口实现类
1、创建用户数据访问接口实现类
在net.huawei.shop.dao包里创建impl子包,在子包里创建UserDaoImpl类
@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 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();
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(2, 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 e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回查询用户
return user;
}
1_、对用户数据访问接口实现类做单元测试
package net.huawei.shop.dao.impl;
import net.huawei.shop.bean.User;
import net.huawei.shop.dao.UserDao;
import org.junit.Test;
/**
* 功能:测试用户数据访问接口实现类
* 作者:华卫
* 日期:2023年06月01日
*/
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 + "]的用户未找到~");
}
}
@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 + "]的用户~");
}
}
@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("444444");
user.setTelephone("15890456780");
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("遗憾,插入用户记录失败~");
}
}
@Test // 测试更新用户
public void testUpdate() {
// 创建用户对象
User user = new User();
// 设置用户对象属性
user.setId(5);
user.setUsername("娃哈哈");
user.setPassword("888888");
user.setTelephone("13978789023");
user.setRegisterTime(new Date());
user.setPopedom(0);
// 创建用户数据访问接口对象
UserDao userDao = new UserDaoImpl();
// 调用用户数据访问接口对象的更新用户方法
int count = userDao.update(user);
// 判断是否成功更新用户
if (count > 0) { // 成功
System.out.println("恭喜,更新用户记录成功~");
} else { // 失败
System.out.println("遗憾,更新用户记录失败~");
}
}
@Test // 测试按标识符删除用户
public void testDeleteById() {
// 定义标识符变量
int id = 5;
// 创建用户数据访问接口对象
UserDao userDao = new UserDaoImpl();
// 调用用户数据访问接口对象的按标识符删除用户方法
int count = userDao.deleteById(id);
// 判断是否成功删除用户
if (count > 0) { // 成功
System.out.println("恭喜,删除用户记录成功~");
} else { // 失败
System.out.println("遗憾,删除用户记录失败~");
}
}
2、创建类别数据访问接口实现类
@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;
}
2_、对类别数据访问接口对象做单元测试
在测试文件夹的net.huawei.shop.dao.impl包里创建TestCategoryDaoImpl类
package net.huawei.shop.dao.impl;
import net.huawei.shop.bean.Category;
import net.huawei.shop.dao.CategoryDao;
import org.junit.Test;
/**
* 功能:测试类别数据访问接口实现类
* 作者:华卫
* 日期:2023年06月02日
*/
public class 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 + "]的类别未找到~");
}
}
}
categories.size() > 0
!categories.isEmpty()
@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("遗憾,类别删除失败~");
}
}
@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) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回插入记录数
return count;
}
@Override // 按标识符删除商品
public int deleteById(int id) {
// 定义删除记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "DELETE FROM t_product WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行更新操作,删除记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回删除记录数
return count;
}
@Override // 更新商品
public int update(Product product) {
// 定义更新记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "UPDATE t_product SET name = ?, price = ?, add_time = ?, category_id = ? WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, product.getName());
pstmt.setDouble(2, product.getPrice());
pstmt.setTimestamp(3, new Timestamp(product.getAddTime().getTime()));
pstmt.setInt(4, product.getCategoryId());
pstmt.setInt(5, product.getId());
// 执行更新操作,更新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回更新记录数
return count;
}
@Override // 按标识符查询商品
public Product findById(int id) {
// 声明商品
Product product = null;
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_product WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 判断结果集是否有记录
if (rs.next()) {
// 实例化商品
product = new Product();
// 利用当前记录字段值去设置商品的属性
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("price"));
product.setAddTime(rs.getTimestamp("add_time"));
product.setCategoryId(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("price"));
product.setAddTime(rs.getTimestamp("add_time"));
product.setCategoryId(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_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) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回类别列表
return products;
}
package net.huawei.shop.dao.impl;
import net.huawei.shop.bean.Product;
import net.huawei.shop.dao.ProductDao;
import org.junit.Test;
/**
* 功能:测试商品数据访问接口实现类
* 作者:华卫
* 日期:2023年06月05日
*/
public class TestProductDaoImpl {
@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 + "]的商品未找到~");
}
}
}
@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 + "]的商品未找到~");
}
}
@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("商品表里没有记录~");
}
}
@Test // 测试插入商品
public void testInsert() {
// 创建商品对象
Product product = new Product();
// 设置商品对象属性
product.setName("晨光签字笔");
product.setPrice(3.0);
product.setAddTime(new Date());
product.setCategoryId(3);
// 创建商品数据访问接口对象
ProductDao productDao = new ProductDaoImpl();
// 调用商品数据访问接口对象的插入商品方法
int count = productDao.insert(product);
// 判断商品是否插入成功
if (count > 0) { // 成功
System.out.println("恭喜,商品插入成功~");
} else { // 失败
System.out.println("遗憾,商品插入失败~");
}
}
@Test // 测试更新商品
public void testUpdate() {
// 创建商品对象
Product product = new Product();
// 设置商品对象属性
product.setId(16);
product.setName("萌萌哒薯片");
product.setPrice(10.0);
product.setAddTime(new Date());
product.setCategoryId(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 = 16;
// 创建商品数据访问接口对象
ProductDao productDao = new ProductDaoImpl();
// 调用商品数据访问接口对象的按标识符删除商品方法
int count = productDao.deleteById(id);
// 判断商品是否删除成功
if (count > 0) { // 成功
System.out.println("恭喜,商品删除成功~");
} else { // 失败
System.out.println("遗憾,商品删除失败~");
}
}
@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) {
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_order 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(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) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回更新记录数
return count;
}
@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) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回订单
return order;
}
@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) {
System.err.println(e.getMessage());
} 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) {
System.err.println(e.getMessage());
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn); // 关闭数据库连接
}
// 返回用户列表
return orders;
}
package net.huawei.shop.dao.impl;
import net.huawei.shop.bean.Order;
import net.huawei.shop.dao.OrderDao;
import org.junit.Test;
/**
* 功能:测试订单数据访问接口实现类
* 作者:华卫
* 日期:2023年06月05日
*/
public class TestOrderDaoImpl {
@Test // 测试按标识符查询订单
public void testFindById() {
// 定义标识符变量
int id = 1;
// 创建订单数据访问接口对象
OrderDao orderDao = new OrderDaoImpl();
// 调用订单数据访问接口对象的按标识符查询订单方法
Order order = orderDao.findById(id);
// 判断是否找到订单
if (order != null) { // 找到
System.out.println(order);
} else { // 未找到
System.out.println("编号为[" + id + "]的订单未找到~");
}
}
}
(七)创建数据访问服务类
package net.huawei.shop.service;
import net.huawei.shop.bean.User;
import net.huawei.shop.dao.UserDao;
import net.huawei.shop.dao.impl.UserDaoImpl;
import java.util.List;
/**
* 功能:用户服务类
* 作者:华卫
* 日期:2023年06月05日
*/
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);
}
}
package net.huawei.shop.service;
import net.huawei.shop.bean.Category;
import net.huawei.shop.dao.CategoryDao;
import net.huawei.shop.dao.impl.CategoryDaoImpl;
import java.util.List;
/**
* 功能:类别服务类
* 作者:华卫
* 日期:2023年06月05日
*/
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();
}
}
package net.huawei.shop.service;
import net.huawei.shop.bean.Product;
import net.huawei.shop.dao.ProductDao;
import net.huawei.shop.dao.impl.ProductDaoImpl;
import java.util.List;
/**
* 功能:商品服务类
* 作者:华卫
* 日期:2023年06月05日
*/
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();
}
}
package net.huawei.shop.service;
import net.huawei.shop.bean.Order;
import net.huawei.shop.dao.OrderDao;
import net.huawei.shop.dao.impl.OrderDaoImpl;
import java.util.List;
/**
* 功能:订单服务类
* 作者:华卫
* 日期:2023年06月05日
*/
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();
}
}