一.实现步骤
创建MySQL数据库simonshop,包含四张表:用户表(t_user)、类别表(t_category)、商品表(t_product)和订单表(t_order)
创建数据库表sql代码如下
/*
Navicat MySQL Data Transfer
Source Server : hwsql
Source Server Version : 50518
Source Host : localhost:3306
Source Database : simonshop
Target Server Type : MYSQL
Target Server Version : 50518
File Encoding : 65001
Date: 2017-02-16 09:21:41
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `t_category`
-- ----------------------------
DROP TABLE IF EXISTS `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;
-- ----------------------------
-- Records of t_category
-- ----------------------------
INSERT INTO `t_category` VALUES ('1', '家用电器');
INSERT INTO `t_category` VALUES ('2', '床上用品');
INSERT INTO `t_category` VALUES ('3', '文具用品');
INSERT INTO `t_category` VALUES ('4', '休闲食品');
-- ----------------------------
-- Table structure for `t_order`
-- ----------------------------
DROP TABLE IF EXISTS `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;
-- ----------------------------
-- Records of t_order
-- ----------------------------
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');
-- ----------------------------
-- Table structure for `t_product`
-- ----------------------------
DROP TABLE IF EXISTS `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;
-- ----------------------------
-- Records of t_product
-- ----------------------------
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');
-- ----------------------------
-- Table structure for `t_user`
-- ----------------------------
DROP TABLE IF EXISTS `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;
-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2016-12-02 08:40:35', '0');
INSERT INTO `t_user` VALUES ('2', '郑晓红', '11111', '13956567889', '2016-12-20 09:51:43', '1');
INSERT INTO `t_user` VALUES ('3', '温志军', '22222', '13956678907', '2016-12-20 09:52:36', '1');
INSERT INTO `t_user` VALUES ('4', '涂文艳', '33333', '15890905678', '2016-12-05 09:52:56', '1');
2.创建Web项目simonshop
3.创建实体类
在src里创建net.hw.shop.bean包,创建四个实体类:User、Category、Product与Order,与四张表t_user、t_category、t_product与t_order一一对应。
实体类User代码
package net.wx.shop.bean;
import java.util.Date;
public class User {
/**
* 用户标识符
*/
private int id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 电话号码
*/
private String telephone;
/**
* 注册时间
*/
private Date registerTime;
/**
* 权限(0:管理员;1:普通用户)
*/
private int popedom;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
实体类Category代码
package net.wx.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 + '\'' +
'}';
}
}
实体类Product
package net.wx.shop.bean;
import java.util.Date;
public class Product {
/**
* 商品标识符
*/
private int id;
/**
* 商品名称
*/
private String name;
/**
* 商品单价
*/
private double price;
/**
* 商品上架时间
*/
private Date addTime;
/**
* 商品所属类别标识符
*/
private int categoryId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", addTime=" + addTime +
", categoryId=" + categoryId +
'}';
}
}
实体类Order代码
package net.wx.shop.bean;
import java.util.Date;
public class Order {
/**
* 订单标识符
*/
private int id;
/**
* 用户名
*/
private String username;
/**
* 联系电话
*/
private String telephone;
/**
* 订单总金额
*/
private double totalPrice;
/**
* 送货地址
*/
private String deliveryAddress;
/**
* 下单时间
*/
private Date orderTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public String getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public Date getOrderTime() {
return orderTime;
}
public void setOrderTime(Date orderTime) {
this.orderTime = orderTime;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", username='" + username + '\'' +
", telephone='" + telephone + '\'' +
", totalPrice=" + totalPrice +
", deliveryAddress='" + deliveryAddress + '\'' +
", orderTime=" + orderTime +
'}';
}
}
创建数据库工具类ConnectionManager
在web\WEB-INF目录下创建lib子目录,添加MySQL驱动程序的jar包
2、在src下创建net.hw.shop.dbutil包,在里面创建ConnectionManager类
package net.wx.shop.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class ConnectionManager {
/**
* 数据库驱动程序
*/
private static final String DRIVER = "com.mysql.jdbc.Driver";
/**
* 数据库统一资源标识符
*/
private static final String URL = "jdbc:mysql://localhost:3306/simonshop";
/**
* 数据库用户名
*/
private static final String USERNAME = "root";
/**
* 数据库密码
*/
private static final String PASSWORD = "123456";
/**
* 私有化构造方法,拒绝实例化
*/
private ConnectionManager() {
}
/**
* 获取数据库连接静态方法
*
* @return 数据库连接对象
*/
public static Connection getConnection() {
// 定义数据库连接
Connection conn = null;
try {
// 安装数据库驱动程序
Class.forName(DRIVER);
// 获得数据库连接
conn = DriverManager.getConnection(URL
+ "?useUnicode=true&characterEncoding=UTF8", USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 返回数据库连接
return conn;
}
/**
* 关闭数据库连接静态方法
*
* @param conn
*/
public static void closeConnection(Connection conn) {
// 判断数据库连接是否为空
if (conn != null) {
// 判断数据库连接是否关闭
try {
if (!conn.isClosed()) {
// 关闭数据库连接
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 测试数据库连接是否成功
*
* @param args
*/
public static void main(String[] args) {
// 获得数据库连接
Connection conn = getConnection();
// 判断是否连接成功
if (conn != null) {
JOptionPane.showMessageDialog(null, "恭喜,数据库连接成功!");
} else {
JOptionPane.showMessageDialog(null, "遗憾,数据库连接失败!");
}
// 关闭数据库连接
closeConnection(conn);
}
}
运行查看链接效果,也可采用数据库连接池,效率更高
4.在src里创建net.hw.shop.dao包,在里面创建UserDao、CategoryDao、ProductDao与OrderDao
用户数据访问接口UserDao
package net.wx.shop.dao;
import java.util.List;
import net.wx.shop.bean.User;
public interface UserDao {
// 插入用户
int insert(User user);
// 按标识符删除用户
int deleteById(int id);
// 更新用户
int update(User user);
// 按标识符查询用户
User findById(int id);
// 按用户名查询用户
List findByUsername(String username);
// 查询全部用户
List findAll();
// 用户登录
User login(String username, String password);
}
类别数据访问接口CategoryDao
package net.wx.shop.dao;
import java.util.List;
import net.wx.shop.bean.Category;
public interface CategoryDao {
// 插入类别
int insert(Category category);
// 按标识符删除类别
int deleteById(int id);
// 更新类别
int update(Category category);
// 按标识符查询类别
Category findById(int id);
// 查询全部类别
List findAll();
}
商品数据访问接口ProductDao
package net.wx.shop.dao;
import java.util.List;
import net.wx.shop.bean.Product;
public interface ProductDao {
// 插入商品
int insert(Product product);
// 按标识符删除商品
int deleteById(int id);
// 更新商品
int update(Product product);
// 按标识符查询商品
Product findById(int id);
// 按类别查询商品
List findByCategoryId(int categoryId);
// 查询全部商品
List findAll();
}
订单数据访问接口OrderDao
package net.wx.shop.dao;
import java.util.List;
import net.wx.shop.bean.Order;
public interface OrderDao {
// 插入订单
int insert(Order order);
// 按标识符删除订单
int deleteById(int id);
// 更新订单
int update(Order order);
// 按标识符查询订单
Order findById(int id);
// 查询最后一个订单
Order findLast();
// 查询全部订单
List findAll();
}
5.数据访问接口实现类XXXDaoImpl及测试类
在src下创建net.hw.shop.dao.impl包,在里面创建UserDaoImpl、CategoryDaoImpl、ProductDaoImpl与OrderDaoImpl。
用户数据访问接口实现类UserDaoImpl
package net.wx.shop.dao.Impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import net.wx.shop.bean.User;
import net.wx.shop.dao.UserDao;
import net.wx.shop.dbutil.ConnectionManager;
public class UserDaoImpl implements UserDao {
/**
* 插入用户
*/
@Override
public int insert(User user) {
// 定义插入记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "INSERT INTO t_user (username, password, telephone, register_time, popedom)"
+ " VALUES (?, ?, ?, ?, ?)";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getTelephone());
pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));
pstmt.setInt(5, user.getPopedom());
// 执行更新操作,插入新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回插入记录数
return count;
}
/**
* 删除用户记录
*/
@Override
public int deleteById(int id) {
// 定义删除记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "DELETE FROM t_user WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行更新操作,删除记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回删除记录数
return count;
}
/**
* 更新用户
*/
@Override
public int update(User user) {
// 定义更新记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "UPDATE t_user SET username = ?, password = ?, telephone = ?,"
+ " register_time = ?, popedom = ? WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getTelephone());
pstmt.setTimestamp(4, new Timestamp(user.getRegisterTime().getTime()));
pstmt.setInt(5, user.getPopedom());
pstmt.setInt(6, user.getId());
// 执行更新操作,更新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回更新记录数
return count;
}
/**
* 按标识符查询用户
*/
@Override
public User findById(int id) {
// 声明用户
User user = null;
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_user WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 判断结果集是否有记录
if (rs.next()) {
// 实例化用户
user = new User();
// 利用当前记录字段值去设置商品类别的属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回用户
return user;
}
@Override
public List findByUsername(String username) {
// 声明用户列表
List users = new ArrayList();
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_user WHERE username = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, username);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 遍历结果集
while (rs.next()) {
// 创建类别实体
User user = new User();
// 设置实体属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
// 将实体添加到用户列表
users.add(user);
}
// 关闭结果集
rs.close();
// 关闭语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回用户列表
return users;
}
@Override
public List findAll() {
// 声明用户列表
List users = new ArrayList();
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_user";
try {
// 创建语句对象
Statement stmt = conn.createStatement();
// 执行SQL,返回结果集
ResultSet rs = stmt.executeQuery(strSQL);
// 遍历结果集
while (rs.next()) {
// 创建用户实体
User user = new User();
// 设置实体属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
// 将实体添加到用户列表
users.add(user);
}
// 关闭结果集
rs.close();
// 关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回用户列表
return users;
}
/**
* 登录方法
*/
@Override
public User login(String username, String password) {
// 定义用户对象
User user = null;
// 获取数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_user WHERE username = ? AND password = ?";
try {
// 创建预备语句对象
PreparedStatement psmt = conn.prepareStatement(strSQL);
// 设置占位符的值
psmt.setString(1, username);
psmt.setString(2, password);
// 执行查询,返回结果集
ResultSet rs = psmt.executeQuery();
// 判断结果集是否有记录
if (rs.next()) {
// 实例化用户对象
user = new User();
// 用记录值设置用户属性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getDate("register_time"));
user.setPopedom(rs.getInt("popedom"));
}
// 关闭结果集
rs.close();
// 关闭预备语句
psmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回用户对象
return user;
}
}
我们需要对用户数据访问接口实现类的各个方法进行单元测试,采用JUnit来进行单元测试。
在项目根目录创建一个test文件夹,然后在项目结构窗口里将其标记为"Tests",这样文件夹颜色变成绿色。
在test文件夹里创建net.hw.shop.dao.impl包,在里面创建测试类TestUserDaoImpl:
(1)编写测试测试类TestUserDaoImpl
package net.wx.shop.dao.impl;
import net.wx.shop.bean.User;
import net.wx.shop.dao.Impl.UserDaoImpl;
import net.wx.shop.dao.UserDao;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class TestUserDaoImpl {
//登录
@Test
public void testLogin(){
String username,password;
username="admin";
password="12345";
UserDao userDao=new UserDaoImpl();
User user=userDao.login(username,password);
if(user !=null){
System.out.println("登录成功!");
}else {
System.out.println("登录失败!");
}
}
//更新
@Test
public void testUpdate(){
//创建用户数据访问对象
UserDao userDao=new UserDaoImpl();
User user=userDao.findById(4);
//修改
user.setPassword("12345");
user.setTelephone("12345678901");
int count=userDao.update(user);
//判断是否成功
if (count>0){
System.out.println("更新成功!");
}else {
System.out.println("更新失败!");
}
user=userDao.findById(4);
System.out.println(user);
}
//插入
@Test
public void testInsert(){
User user=new User();
user.setId(5);
user.setUsername("朱坚强");
user.setPassword("12345");
user.setTelephone("17748118416");
user.setRegisterTime(new Timestamp(new Date().getTime()));
user.setPopedom(1);
UserDao dao = new UserDaoImpl();
int count = dao.insert(user);
if(count>0){
System.out.println("恭喜,记录插入成功!");
}else {
System.out.println("遗憾,记录插入失败!");
}
}
//删除
@Test
public void testDeleteById(){
UserDao dao=new UserDaoImpl();
int count=dao.deleteById(3);
if(count>0){
System.out.println("删除数据成功!");
}else {
System.out.println("删除数据失败!");
}
}
//查找全部
@Test
public void testFindAll(){
UserDao dao=new UserDaoImpl();
List users=dao.findAll();
if (users.size()>0){
for (User user:users){
System.out.println(user);
}
}
}
//按用户名查找用户
@Test
public void testFindByUsername(){
UserDao dao=new UserDaoImpl();
String name="admin";
List users=dao.findByUsername(name);
if (users.size()>0){
for (User user:users){
System.out.println(user);
}
}
}
//按ID查找用户
@Test
public void testFindById(){
UserDao dao=new UserDaoImpl();
User user=dao.findById(2);
System.out.println(user);
}
}
运行代码查看是否正确
类别数据访问接口实现类CategoryDaoImpl
package net.wx.shop.dao.Impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import net.wx.shop.bean.Category;
import net.wx.shop.dao.CategoryDao;
import net.wx.shop.dbutil.ConnectionManager;
public class CategoryDaoImpl implements CategoryDao {
/**
* 插入类别
*/
@Override
public int insert(Category category) {
// 定义插入记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "INSERT INTO t_category (name) VALUES (?)";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, category.getName());
// 执行更新操作,插入新录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回插入记录数
return count;
}
/**
* 删除类别
*/
@Override
public int deleteById(int id) {
// 定义删除记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "DELETE FROM t_category WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行更新操作,删除记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回删除记录数
return count;
}
/**
* 更新类别
*/
@Override
public int update(Category category) {
// 定义更新记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "UPDATE t_category SET name = ? WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, category.getName());
pstmt.setInt(2, category.getId());
// 执行更新操作,更新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回更新记录数
return count;
}
/**
* 按标识符查询类别
*/
@Override
public Category findById(int id) {
// 声明商品类别
Category category = null;
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_category WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 判断结果集是否有记录
if (rs.next()) {
// 实例化商品类别
category = new Category();
// 利用当前记录字段值去设置商品类别的属性
category.setId(rs.getInt("id"));
category.setName(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回商品类别
return category;
}
/**
* 查询全部类别
*/
@Override
public List findAll() {
// 声明类别列表
List categories = 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()) {
// 创建类别实体
Category category = new Category();
// 设置实体属性
category.setId(rs.getInt("id"));
category.setName(rs.getString("name"));
// 将实体添加到类别列表
categories.add(category);
}
// 关闭结果集
rs.close();
// 关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回类别列表
return categories;
}
}
创建测试类TestCategoryDaoImpl,编写测试TestCategoryDaoImpl
package net.wx.shop.dao.impl;
import net.wx.shop.bean.Category;
import net.wx.shop.dao.CategoryDao;
import net.wx.shop.dao.Impl.CategoryDaoImpl;
import org.junit.Test;
import java.util.List;
public class TestCategoryDaoImpl {
//查找全部
@Test
public void testFindAll() {
CategoryDao categoryDao = new CategoryDaoImpl();
List categories = categoryDao.findAll();
if (categories.size() > 0) {
for (Category category : categories) {
System.out.println(category);
}
} else {
System.out.println("没有商品类别!");
}
}
//插入
@Test
public void testInsert() {
Category category = new Category();
category.setId(5);
category.setName("厨房用品");
CategoryDao dao = new CategoryDaoImpl();
int count = dao.insert(category);
if (count > 0) {
System.out.println("恭喜,记录插入成功!");
} else {
System.out.println("遗憾,记录插入失败!");
}
}
//删除
@Test
public void testDeleteById() {
CategoryDao dao = new CategoryDaoImpl();
int count = dao.deleteById(3);
if (count > 0) {
System.out.println("删除数据成功!");
} else {
System.out.println("删除数据失败!");
}
}
//更新
@Test
public void testUpdate() {
CategoryDao categoryDao = new CategoryDaoImpl();
Category category = categoryDao.findById(3);
category.setId(1);
category.setName("护肤用品");
int count = categoryDao.update(category);
//判断是否成功
if (count > 0) {
System.out.println("更新成功!");
} else {
System.out.println("更新失败!");
}
category = categoryDao.findById(4);
System.out.println(category);
}
//id查找
@Test
public void testFindById() {
CategoryDao categoryDao = new CategoryDaoImpl();
Category category = categoryDao.findById(2);
System.out.println(category);
}
}
运行代码是否正确查找错误
商品数据访问接口实现类ProductDaoImpl
package net.wx.shop.dao.Impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import net.wx.shop.bean.Product;
import net.wx.shop.dao.ProductDao;
import net.wx.shop.dbutil.ConnectionManager;
public class ProductDaoImpl implements ProductDao {
/**
* 插入商品
*/
@Override
public int insert(Product product) {
// 定义插入记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "INSERT INTO t_product (name, price, add_time, category_id)" + " VALUES (?, ?, ?, ?)";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, product.getName());
pstmt.setDouble(2, product.getPrice());
pstmt.setTimestamp(3, new Timestamp(product.getAddTime().getTime()));
pstmt.setInt(4, product.getCategoryId());
// 执行更新操作,插入新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回插入记录数
return count;
}
/**
* 删除商品
*/
@Override
public int deleteById(int id) {
// 定义删除记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "DELETE FROM t_product WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行更新操作,删除记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回删除记录数
return count;
}
/**
* 更新商品
*/
@Override
public int update(Product product) {
// 定义更新记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "UPDATE t_product SET name = ?, price = ?, add_time = ?,"
+ " category_id = ? WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, product.getName());
pstmt.setDouble(2, product.getPrice());
pstmt.setTimestamp(3, new Timestamp(product.getAddTime().getTime()));
pstmt.setInt(4, product.getCategoryId());
pstmt.setInt(5, product.getId());
// 执行更新操作,更新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回更新记录数
return count;
}
/**
* 按标识符查找商品
*/
@Override
public Product findById(int id) {
// 声明商品
Product product = null;
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_product WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 判断结果集是否有记录
if (rs.next()) {
// 实例化商品
product = new Product();
// 利用当前记录字段值去设置商品类别的属性
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("price"));
product.setAddTime(rs.getTimestamp("add_time"));
product.setCategoryId(rs.getInt("category_id"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回商品
return product;
}
/**
* 按类别查询商品
*/
@Override
public List findByCategoryId(int categoryId) {
// 定义商品列表
List 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);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回商品列表
return products;
}
/**
* 查询全部商品
*/
@Override
public List findAll() {
// 声明商品列表
List 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) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回商品列表
return products;
}
}
创建测试类TestProductDaoImpl,编写测试TestProductDaoImpl所有方法
package net.wx.shop.dao.impl;
import net.wx.shop.bean.Product;
import net.wx.shop.bean.User;
import net.wx.shop.dao.CategoryDao;
import net.wx.shop.dao.Impl.CategoryDaoImpl;
import net.wx.shop.dao.Impl.ProductDaoImpl;
import net.wx.shop.dao.ProductDao;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class TestProductDaoImpl {
@Test
public void testInsert(){
Product product=new Product();
product.setId(16);
product.setName("苹果电脑");
product.setPrice(8000);
product.setAddTime(new Timestamp(new Date().getTime()));
product.setCategoryId(3);
ProductDao dao=new ProductDaoImpl();
int count=dao.insert(product);
if(count>0){
System.out.println("恭喜,记录插入成功!");
}else {
System.out.println("遗憾,记录插入失败!");
}
}
@Test
public void testDeleteById(){
ProductDao dao=new ProductDaoImpl();
int count=dao.deleteById(3);
if(count>0){
System.out.println("删除数据成功!");
}else {
System.out.println("删除数据失败!");
}
}
//
@Test
public void testUpdate(){
ProductDao dao=new ProductDaoImpl();
Product product=dao.findById(3);
product.setId(16);
product.setName("苹果电脑");
product.setPrice(8000);
product.setAddTime(new Timestamp(new Date().getTime()));
product.setCategoryId(3);
int count=dao.update(product);
if(count>0){
System.out.println("恭喜,记录更新成功!");
}else {
System.out.println("遗憾,记录更新失败!");
}
}
//id查找
@Test
public void testFindById(){
ProductDao dao=new ProductDaoImpl();
Product product=dao.findById(3);
System.out.println(product);
}
//
@Test
public void testFindByCategoryId(){
ProductDao productDao=new ProductDaoImpl();
int categoryId=1;
CategoryDao categoryDao=new CategoryDaoImpl();
if (categoryDao.findById(categoryId)!=null){
String catedoryName=categoryDao.findById(categoryId).getName();
List products=productDao.findByCategoryId(categoryId);
if (products.size()>0){
for (Product product:products){
System.out.println(product);
}
}else {
System.out.println("["+catedoryName+"]没有类别商品!");
}
}else {
System.out.println("类别编号["+categoryId+"]不存在!");
}
}
//
@Test
public void testFindAll(){
ProductDao productDao=new ProductDaoImpl();
List products=productDao.findAll();
System.out.println(products);
}
}
运行代码
订单数据访问接口实现类OrderDaoImpl
package net.wx.shop.dao.Impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import net.wx.shop.bean.Order;
import net.wx.shop.dao.OrderDao;
import net.wx.shop.dbutil.ConnectionManager;
public class OrderDaoImpl implements OrderDao {
/**
* 插入订单
*/
@Override
public int insert(Order order) {
// 定义插入记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "INSERT INTO t_order (username, telephone, total_price, delivery_address, order_time)"
+ " VALUES (?, ?, ?, ?, ?)";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, order.getUsername());
pstmt.setString(2, order.getTelephone());
pstmt.setDouble(3, order.getTotalPrice());
pstmt.setString(4, order.getDeliveryAddress());
pstmt.setTimestamp(5, new Timestamp(order.getOrderTime().getTime()));
// 执行更新操作,插入记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回插入记录数
return count;
}
/**
* 删除订单
*/
@Override
public int deleteById(int id) {
// 定义删除记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "DELETE FROM t_order WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行更新操作,删除记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回删除记录数
return count;
}
/**
* 更新订单
*/
@Override
public int update(Order order) {
// 定义更新记录数
int count = 0;
// 获得数据库连接
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "UPDATE t_order SET username = ?, telephone = ?, total_price = ?,"
+ " delivery_address = ?, order_time = ? WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, order.getUsername());
pstmt.setString(2, order.getTelephone());
pstmt.setDouble(3, order.getTotalPrice());
pstmt.setString(4, order.getDeliveryAddress());
pstmt.setTimestamp(5, new Timestamp(order.getOrderTime().getTime()));
pstmt.setInt(6, order.getId());
// 执行更新操作,更新记录
count = pstmt.executeUpdate();
// 关闭预备语句对象
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回更新记录数
return count;
}
/**
* 查询最后一个订单
*/
@Override
public Order findLast() {
// 声明订单
Order order = null;
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_order";
try {
// 创建语句对象
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
// 执行SQL,返回结果集
ResultSet rs = stmt.executeQuery(strSQL);
// 定位到最后一条记录
if (rs.last()) {
// 创建订单实体
order = new Order();
// 设置实体属性
order.setId(rs.getInt("id"));
order.setUsername(rs.getString("username"));
order.setTelephone(rs.getString("telephone"));
order.setTotalPrice(rs.getDouble("total_price"));
order.setDeliveryAddress(rs.getString("delivery_address"));
order.setOrderTime(rs.getTimestamp("order_time"));
}
// 关闭结果集
rs.close();
// 关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回订单对象
return order;
}
/**
* 按标识符查询订单
*/
@Override
public Order findById(int id) {
// 声明订单
Order order = null;
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_order WHERE id = ?";
try {
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 判断结果集是否有记录
if (rs.next()) {
// 实例化订单
order = new Order();
// 利用当前记录字段值去设置订单的属性
order.setId(rs.getInt("id"));
order.setUsername(rs.getString("username"));
order.setTelephone(rs.getString("telephone"));
order.setDeliveryAddress(rs.getString("delivery_address"));
order.setOrderTime(rs.getTimestamp("order_time"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);
}
// 返回订单
return order;
}
/**
* 查询全部订单
*/
@Override
public List findAll() {
// 声明订单列表
List orders = new ArrayList();
// 获取数据库连接对象
Connection conn = ConnectionManager.getConnection();
// 定义SQL字符串
String strSQL = "SELECT * FROM t_order";
try {
// 创建语句对象
Statement stmt = conn.createStatement();
// 执行SQL,返回结果集
ResultSet rs = stmt.executeQuery(strSQL);
// 遍历结果集
while (rs.next()) {
// 创建订单实体
Order order = new Order();
// 设置实体属性
order.setId(rs.getInt("id"));
order.setUsername(rs.getString("username"));
order.setTelephone(rs.getString("telephone"));
order.setDeliveryAddress(rs.getString("delivery_address"));
order.setOrderTime(rs.getTimestamp("order_time"));
// 将实体添加到订单列表
orders.add(order);
}
// 关闭结果集
rs.close();
// 关闭语句对象
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
ConnectionManager.closeConnection(conn);
}
// 返回用户列表
return orders;
}
}
创建测试类TestOrderDaoImpl,编写测试方法
package net.wx.shop.dao.impl;
import net.wx.shop.bean.Order;
import net.wx.shop.dao.Impl.OrderDaoImpl;
import net.wx.shop.dao.OrderDao;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class TestOrderDaoImpl {
@Test
public void testFinAll() {
OrderDao orderDao = new OrderDaoImpl();
List orders = orderDao.findAll();
if (orders.size()>0){
for (Order order:orders){
System.out.println(order);
}
}else {
System.out.println("没有订单!");
}
}
//
@Test
public void testInsert(){
Order order=new Order();
order.setId(3);
order.setUsername("admin");
order.setTotalPrice(2000);
order.setOrderTime(new Timestamp(new Date().getTime()));
order.setDeliveryAddress("泸职院信息工程系");
OrderDao dao=new OrderDaoImpl();
int count=dao.insert(order);
if(count>0){
System.out.println("恭喜,记录插入成功!");
}else {
System.out.println("遗憾,记录插入失败!");
}
}
//
@Test
public void testDeleteById(){
OrderDao dao=new OrderDaoImpl();
int count=dao.deleteById(2);
if(count>0){
System.out.println("删除数据成功!");
}else {
System.out.println("删除数据失败!");
}
}
//更新
@Test
public void testUpdate(){
OrderDao dao=new OrderDaoImpl();
Order order=dao.findById(1);
order.setId(4);
order.setUsername("admin1");
order.setTotalPrice(2000);
order.setOrderTime(new Timestamp(new Date().getTime()));
order.setDeliveryAddress("泸职院信息工程系");
OrderDao orderDao=new OrderDaoImpl();
int count=orderDao.update(order);
if (count>0){
System.out.println("更新成功!");
}else {
System.out.println("更新失败!");
}
}
@Test
public void testFindById(){
OrderDao dao=new OrderDaoImpl();
Order order=dao.findById(1);
System.out.println(order);
}
//
@Test
public void testFindLast(){
OrderDao dao=new OrderDaoImpl();
Order order=dao.findLast();
System.out.println(order);
}
}
运行代码测试方法
删除所有订单记录。此时,再运行测试方法testFinAll(),结果如下:
6.创建数据访问服务类XXXService
下面编写server层的实体类和测试类
用户服务类UserService
package net.wx.shop.service;
import java.util.List;
import net.wx.shop.bean.User;
import net.wx.shop.dao.Impl.UserDaoImpl;
import net.wx.shop.dao.UserDao;
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 findUsersByUsername(String username) {
return userDao.findByUsername(username);
}
public List findAllUsers() {
return userDao.findAll();
}
public User login(String username, String password) {
return userDao.login(username, password);
}
}
类别服务类CategoryService
package net.wx.shop.service;
import java.util.List;
import net.wx.shop.bean.Category;
import net.wx.shop.dao.CategoryDao;
import net.wx.shop.dao.Impl.CategoryDaoImpl;
public class CategoryService {
/**
* 声明类别数据访问对象
*/
private CategoryDao categoryDao = new CategoryDaoImpl();
public int addCategory(Category category) {
return categoryDao.insert(category);
}
public int deleteCategoryById(int id) {
return categoryDao.deleteById(id);
}
public int updateCategory(Category category) {
return categoryDao.update(category);
}
public Category findCategoryById(int id) {
return categoryDao.findById(id);
}
public List findAllCategories() {
return categoryDao.findAll();
}
}
商品服务类ProductService
package net.wx.shop.service;
import java.util.List;
import net.wx.shop.bean.Product;
import net.wx.shop.dao.ProductDao;
import net.wx.shop.dao.Impl.ProductDaoImpl;
public class ProductService {
/**
* 声明商品数据访问对象
*/
private ProductDao productDao = new ProductDaoImpl();
public int addProduct(Product product) {
return productDao.insert(product);
}
public int deleteProductById(int id) {
return productDao.deleteById(id);
}
public int updateProduct(Product product) {
return productDao.update(product);
}
public Product findProductById(int id) {
return productDao.findById(id);
}
public List findProductsByCategoryId(int categoryId) {
return productDao.findByCategoryId(categoryId);
}
public List findAllProducts() {
return productDao.findAll();
}
}
订单服务类OrderService
package net.wx.shop.service;
import java.util.List;
import net.wx.shop.bean.Order;
import net.wx.shop.dao.OrderDao;
import net.wx.shop.dao.Impl.OrderDaoImpl;
public class OrderService {
/**
* 声明订单数据访问对象
*/
OrderDao orderDao = new OrderDaoImpl();
public int addOrder(Order order) {
return orderDao.insert(order);
}
public int deleteOrderById(int id) {
return orderDao.deleteById(id);
}
public int updateOrder(Order order) {
return orderDao.update(order);
}
public Order findOrderById(int id) {
return orderDao.findById(id);
}
public Order findLastOrder() {
return orderDao.findLast();
}
public List findAllOrders() {
return orderDao.findAll();
}
}
创建四个测试类TestUserService、TestCategoryService、TestProductService与TestOrderService,编写测试方法测试四个服务类里的各个方法。
创建测试类TestUserService,编写测试方法
package net.wx.shop.service;
import net.wx.shop.bean.User;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class TestUserService {
@Test
public void testAddUser() {
User user = new User();
user.setUsername("招娣");
user.setPassword("123456");
user.setTelephone("14678118412");
user.setRegisterTime(new Timestamp(new Date().getTime()));
user.setId(7);
user.setPopedom(1);
UserService service = new UserService();
int count = service.addUser(user);
if (count > 0) {
System.out.println("记录插入成功!");
} else {
System.out.println("记录插入失败!");
}
}
@Test
public void testLogin() {
String username, password;
username = "admin";
password = "12345";
UserService service = new UserService();
User user = service.login(username, password);
if (user != null) {
System.out.println("登录成功!");
} else {
System.out.println("登录失败!");
}
}
@Test
public void testDeleteUserById() {
UserService service = new UserService();
int count = service.deleteUserById(3);
if (count > 0) {
System.out.println("删除数据成功!");
} else {
System.out.println("删除数据失败!");
}
}
@Test
public void testUpdateUser() {
UserService service = new UserService();
User user = service.findUserById(2);
user.setPopedom(0);
user.setPassword("135790");
int count = service.updateUser(user);
if (count > 0) {
System.out.println("记录更新成功!");
user = service.findUserById(1);
System.out.println(user);
} else {
System.out.println("记录更新失败!");
}
}
@Test
public void testFindUserById() {
UserService service = new UserService();
User user = service.findUserById(2);
System.out.println(user);
}
@Test
public void testFindUsersByUsername() {
UserService service = new UserService();
String name = "admin";
List users = service.findUsersByUsername(name);
if (users.size() > 0) {
for (User user : users) {
System.out.println(user);
}
}
}
@Test
public void testFindAllUsers() {
UserService service = new UserService();
List users = service.findAllUsers();
System.out.println(users);
}
}
创建测试类TestCategoryServicee,编写测试方法
package net.wx.shop.service;
import net.wx.shop.bean.Category;
import org.junit.Test;
import java.util.List;
public class TestCategoryService {
@Test
public void testAddCategory() {
Category category = new Category();
category.setId(6);
category.setName("厨房用品");
CategoryService service = new CategoryService();
int count = service.addCategory(category);
if (count > 0) {
System.out.println("恭喜,记录加入成功!");
} else {
System.out.println("遗憾,记录加入失败!");
}
}
@Test
public void testDeleteCategoryById() {
CategoryService service = new CategoryService();
int count = service.deleteCategoryById(4);
if (count > 0) {
System.out.println("删除数据成功!");
} else {
System.out.println("删除数据失败!");
}
}
//更新
@Test
public void testUpdateCategory() {
CategoryService service = new CategoryService();
Category category = service.findCategoryById(3);
category.setId(1);
category.setName("护肤用品");
int count = service.updateCategory(category);
//判断是否成功
if (count > 0) {
System.out.println("更新成功!");
} else {
System.out.println("更新失败!");
}
category = service.findCategoryById(3);
System.out.println(category);
}
//id查找
@Test
public void testFindCategoryById() {
CategoryService service = new CategoryService();
Category category = service.findCategoryById(2);
System.out.println(category);
}
//查找全部
@Test
public void testFindAll(){
CategoryService service=new CategoryService();
List categories=service.findAllCategories();
if (categories.size()>0){
for (Category category:categories){
System.out.println(category);
}
}else {
System.out.println("没有商品类别!");
}
}
}
创建测试类TestProductService,编写测试方法
package net.wx.shop.service;
import net.wx.shop.bean.Product;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class TestProductService {
@Test
public void testAddProduct() {
Product product = new Product();
product.setId(16);
product.setName("苹果电脑");
product.setPrice(8000);
product.setAddTime(new Timestamp(new Date().getTime()));
product.setCategoryId(3);
ProductService service = new ProductService();
int count = service.addProduct(product);
if (count > 0) {
System.out.println("恭喜,记录插入成功!");
} else {
System.out.println("遗憾,记录插入失败!");
}
}
@Test
public void testDeleteProductById(){
ProductService service=new ProductService();
int count=service.deleteProductById(3);
if(count>0){
System.out.println("删除数据成功!");
}else {
System.out.println("删除数据失败!");
}
}
@Test
public void testUpdateProduct(){
ProductService service=new ProductService();
Product product=service.findProductById(3);
product.setId(16);
product.setName("苹果电脑");
product.setPrice(8000);
product.setAddTime(new Timestamp(new Date().getTime()));
product.setCategoryId(3);
int count=service.updateProduct(product);
if(count>0){
System.out.println("恭喜,记录更新成功!");
}else {
System.out.println("遗憾,记录更新失败!");
}
}
//id查找
@Test
public void testFindProductById(){
ProductService service=new ProductService();
Product product=service.findProductById(3);
System.out.println(product);
}
@Test
public void testFindByCategoryId(){
ProductService productService=new ProductService();
int categoryId=1;
CategoryService categoryService=new CategoryService();
if (categoryService.findCategoryById(categoryId)!=null){
String catedoryName=categoryService.findCategoryById(categoryId).getName();
List products=productService.findProductsByCategoryId(categoryId);
if (products.size()>0){
for (Product product:products){
System.out.println(product);
}
}else {
System.out.println("["+catedoryName+"]没有类别商品!");
}
}else {
System.out.println("类别编号["+categoryId+"]不存在!");
}
}
//
@Test
public void testFindAllProducts(){
ProductService service=new ProductService();
List products=service.findAllProducts();
System.out.println(products);
}
}
创建测试类TestOrderService,编写测试方法
package net.wx.shop.service;
import net.wx.shop.bean.Order;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
public class TestOrderService {
//添加
@Test
public void testAddOrder() {
Order order = new Order();
order.setId(5);
order.setUsername("admin2");
order.setTotalPrice(4000);
order.setOrderTime(new Timestamp(new Date().getTime()));
order.setDeliveryAddress("泸职院信息工程系");
OrderService service = new OrderService();
int count = service.addOrder(order);
if (count > 0) {
System.out.println("恭喜,记录加入成功!");
} else {
System.out.println("遗憾,记录加入失败!");
}
}
//删除
@Test
public void testDeleteOrderById() {
OrderService service = new OrderService();
int count = service.deleteOrderById(2);
if (count > 0) {
System.out.println("删除数据成功!");
} else {
System.out.println("删除数据失败!");
}
}
//更新
@Test
public void testUpdateOrder() {
OrderService service = new OrderService();
Order order = service.findOrderById(3);
order.setId(4);
order.setUsername("admin1");
order.setTotalPrice(2000);
order.setOrderTime(new Timestamp(new Date().getTime()));
order.setDeliveryAddress("泸职院信息工程系");
OrderService orderService = new OrderService();
int count = orderService.updateOrder(order);
if (count > 0) {
System.out.println("更新成功!");
} else {
System.out.println("更新失败!");
}
}
@Test
public void testFindOrderById() {
OrderService service = new OrderService();
Order order = service.findOrderById(1);
System.out.println(order);
}
//
@Test
public void testFindLastOrder() {
OrderService service = new OrderService();
Order order = service.findLastOrder();
System.out.println(order);
}
@Test
public void testFinAllOrders() {
OrderService service = new OrderService();
List orders = service.findAllOrders();
if (orders.size() > 0) {
for (Order order : orders) {
System.out.println(order);
}
} else {
System.out.println("没有订单!");
}
}
}