一、創(chuàng)建數(shù)據庫和表
1、創(chuàng)建數(shù)據庫
- 數(shù)據庫 -
simonshop
2、創(chuàng)建用戶表
創(chuàng)建用戶表結構 - t_user
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) DEFAULT NULL,
`telephone` varchar(11) DEFAULT NULL,
`register_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`popedom` int(11) DEFAULT NULL COMMENT '0:管理員;1:普通用戶',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
- 在用戶表里插入記錄
INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2021-12-02 08:40:35', '0');
INSERT INTO `t_user` VALUES ('2', '鄭曉紅', '11111', '13956567889', '2022-12-20 09:51:43', '1');
INSERT INTO `t_user` VALUES ('3', '溫志軍', '22222', '13956678907', '2022-12-20 09:52:36', '1');
INSERT INTO `t_user` VALUES ('4', '涂文艷', '33333', '15890905678', '2022-12-05 09:52:56', '1');
3、創(chuàng)建類別表
- 創(chuàng)建類別表結構 -
t_category
CREATE TABLE `t_category` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品類別標識符',
`name` varchar(100) NOT NULL COMMENT '商品類別名稱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
- 在類別表里插入記錄
INSERT INTO `t_category` VALUES ('1', '家用電器');
INSERT INTO `t_category` VALUES ('2', '床上用品');
INSERT INTO `t_category` VALUES ('3', '文具用品');
INSERT INTO `t_category` VALUES ('4', '休閑食品');
4、創(chuàng)建商品表
- 創(chuàng)建商品表結構 -
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、創(chuàng)建訂單表
創(chuàng)建訂單表結構 - t_order
CREATE TABLE `t_order` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '訂單標識符',
`username` varchar(20) DEFAULT NULL COMMENT '用戶名',
`telephone` varchar(11) DEFAULT NULL COMMENT '電話號碼',
`total_price` double DEFAULT NULL COMMENT '總金額',
`delivery_address` varchar(50) DEFAULT NULL COMMENT '送貨地址',
`order_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '下單時間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
- 在訂單表里插入記錄
INSERT INTO `t_order` VALUES ('1', '鄭曉紅', '13956567889', '2000', '瀘職院信息工程系', '2016-12-25 17:12:36');
INSERT INTO `t_order` VALUES ('2', '溫志軍', '13956678907', '1000', '瀘職院機械工程系', '2016-12-02 17:12:17');
二、創(chuàng)建Simonshop項目
1、創(chuàng)建web項目
- 創(chuàng)建項目名稱與保存位置
- 單機【finsh】
2、修改Artifacts名稱:simonshop
- 將Artifact名稱改為
simonshiop
3、重新部署項目
- 切換到【server】選項卡
4、編輯首頁
- 首頁 -
index.jsp
<%@ page import="java.util.Date" %><%--
Created by IntelliJ IDEA.
User: HW
Date: 2023/5/29
Time: 15:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首頁</title>
</head>
<body>
<h1 style="color: blue; text-align:center">Java Web實訓項目:西蒙購物網</h1>
<h3 style="text-align: center"><%= new Date()%></h3>
<p style="text-align: center"><a href="login.jsp">跳轉到登錄界面</a> </p>
</body>
</html>
5、啟動應用,查看效果
三、創(chuàng)建實體類
- 創(chuàng)建四個實體類:
User
、Category
、Product
與Order
1、用戶實體類
- 創(chuàng)建
ner.xyx.shop.bean
包,在包里創(chuàng)建用戶實體類 -User
package net.xyx.shop.bean;
import java.util.Date;
public class User {
private int id;//用戶標識符
private String username;//用戶名
private String password;//密碼
private String telephone;//電話
private Date registerTime;//注冊時間
private int popedom;//權限(0:管理員;1:普通用戶)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString(){
return "User{" +
"id=" + id +
",password=" + password +
",telephone= " + telephone +
",registerTime=" + registerTime +
",popedom=" + popedom + '\'' +
'}';
}
}
2、創(chuàng)建類別實體類
- 創(chuàng)建
ner.xyx.shop.bean
包,在包里創(chuàng)建訂單實體類 -Category
package net.xyx.shop.bean;
public class Category {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString(){
return "Category{" +
"id=" + id +
",name=" + name + '\'' +
'}';
}
}
3、創(chuàng)建商品實體類
- 創(chuàng)建
ner.xyx.shop.bean
包,在包里創(chuàng)建訂單實體類 -Category
package net.xyx.shop.bean;
import java.util.Date;
public class Product {
private int id;
private String name;
private double price;
private Date addTime;
private int categotyId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public int getCategotyId() {
return categotyId;
}
public void setCategotyId(int categotyId) {
this.categotyId = categotyId;
}
@Override
public String toString() {
return "Product{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", addTime=" + addTime +
", categotyId=" + categotyId +
'}';
}
}
``
## 4、創(chuàng)建訂單實體類
- 創(chuàng)建`ner.xyx.shop.bean`包,在包里創(chuàng)建訂單實體類 - `Order`
- 代碼如下
```xml
package net.xyx.shop.bean;
import java.util.Date;
public class Order {
private int id;
private String username;
private String telehpone;
private double totalPrice;
private String deliveryAddress;
private Date orderTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelehpone() {
return telehpone;
}
public void setTelehpone(String telehpone) {
this.telehpone = telehpone;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
public String getDeliveryAddress() {
return deliveryAddress;
}
public void setDeliveryAddress(String deliveryAddress) {
this.deliveryAddress = deliveryAddress;
}
public Date getOrderTime() {
return orderTime;
}
public void setOrderTime(Date orderTime) {
this.orderTime = orderTime;
}
@Override
public String toString() {
return "Order{" +
"id=" + id +
", username='" + username + '\'' +
", telehpone='" + telehpone + '\'' +
", totalPrice=" + totalPrice +
", deliveryAddress='" + deliveryAddress + '\'' +
", orderTime=" + orderTime +
'}';
}
}
三、創(chuàng)建數(shù)據庫工具類
1、添加數(shù)據庫驅動程序包
- 在\WEB-INF里創(chuàng)建
lib
子目錄,添加MySQL驅動程序的 - 將數(shù)據庫驅動程序包作為庫添加到項目
2、創(chuàng)建數(shù)據庫連接管理類
- 創(chuàng)建
net.xyx.shop.dbutil
包,在里面創(chuàng)建ConnectionManager
類 - 原代碼
3、測試數(shù)據庫連接是否成功
4、數(shù)據庫連接的常見錯誤
(1)、數(shù)據庫驅動程序名稱寫錯誤
(2)、數(shù)據庫沒找到
5、創(chuàng)建數(shù)據訪問接口
(1)、創(chuàng)建用戶數(shù)據訪問接口
- 在
net.xyx.shop
根包里創(chuàng)建dao
子包,在子包里創(chuàng)建UserDao
接口
package net.xyx.shop.dao;
import net.xyx.shop.bean.User;
import java.util.List;
public interface UserDao {
int insert(User user);//插入用戶
int deleteById(int id);//按標識符刪除用戶
int update(User user);//更新用戶
User findById(int id);//按標識符查詢用戶
List<User> findByUsername(String username);//按用戶名查找用戶
List<User> findAll();//查詢全部用戶
User login (String username,String password);//用戶登錄
}
(2)、類別數(shù)據訪問接口CaregoryDao
- 在
net.xyx.shop
根包里創(chuàng)建dao
子包,在子包里創(chuàng)建CaregoryDao
接口
package net.xyx.shop.dao;
import net.xyx.shop.bean.Category;
import java.util.List;
/**
* 功能:類別數(shù)據訪問接口
* 作者:XYX
*/
public interface CategoryDao {
int insert(Category category);//插入類別
int deleteById(int id);//按標識符刪除類別
int update(Category category);//更新類別
Category findById(int id);//按標識符查詢類別
List<Category>findAll();//查詢全部類別
}
(3)、創(chuàng)建商品數(shù)據訪問接口ProductDao
- 在
net.xyx.shop
根包里創(chuàng)建dao
子包,在子包里創(chuàng)建ProductDao
接口
package net.xyx.shop.dao;
import net.xyx.shop.bean.Product;
import java.util.List;
public interface ProductDao {
int insert(Product product);//插入商品
int deleteById(int id);//按標識符刪除商品
int update(Product product);//更新商品
Product findById(int id);//按標識符查詢商品
List<Product> findByCategoryId (int categoryId);//按類別標識符查詢商品
List<Product> findAll();//查詢全部商品
}
(4)、訂單數(shù)據訪問接口OrderDao
- 在
net.xyx.shop
根包里創(chuàng)建dao
子包,在子包里創(chuàng)建OrderDao
接口
package net.xyx.shop.dao;
import net.xyx.shop.bean.Order;
import java.util.List;
public interface OrderDao {
int insert(Order order);//插入訂單
int deleteById(int id);//按標識符刪除訂單
int update(Order order);//更新訂單
Order findById(int id);//按標識符查詢訂單
Order findLast();//查詢左后一個訂單
List<Order>findAll();//查詢全部訂單
}
6、數(shù)據訪問接口實現(xiàn)類DaoImpl
(1)、創(chuàng)建用戶數(shù)據訪問接口實現(xiàn)類
- 在
net.xyx.shop.dao
包里創(chuàng)建impl
子包,在子包里創(chuàng)建UserDaoImpl
類 - 實現(xiàn)
UserDao
接口
① 編寫插入用戶方法
@Override//插入用戶方法
public int insert(User user) {
//定義插入記錄數(shù)
int count = 0;
//獲取數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
try {
//定義SQL字符串
String strSQL = "INSERT INTO t_user (username,password, telephone, register_time, popedom) VALUES(?,?,?,?,?)";
//創(chuàng)建預備語句對象
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());
//執(zhí)行更新操作,插入新記錄
count = pstmt.executeUpdate();
//關閉預備語句對象
pstmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);//關閉數(shù)據庫連接
}
//返回插入記錄
return count;
}
②邊界刪除用戶方法
@Override//按標識刪除用戶
public int deleteById(int id) {
//定義刪除記錄數(shù)
int count = 0;
//獲取數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
try {
//定義SQL字符串
String strSQL = "DELETE FROM t_user WHERE id=?";
//創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
//設置占位符的值
pstmt.setInt(1,id);
//執(zhí)行更新操作,插入新記錄
count = pstmt.executeUpdate();
//關閉預備語句對象
pstmt.close();
}catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn);//關閉數(shù)據庫連接
}
//返回刪除記錄數(shù)
return count;
}
③編寫更新用戶方法
@Override//按標識符更新用戶
public int update(User user) {
//定義更新用戶記錄數(shù)
int count = 0;
//獲取數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
try {
//定義SQL字符串
String strSQL = "UPDATE t_user SET username=?,password=?, telephone=?, register_time = ?, popedom=?," +
"WHERE id = ?";
//創(chuàng)建預備語句對象
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());
//執(zhí)行更新操作,更新記錄
count = pstmt.executeUpdate();
//關閉預備語句對象
pstmt.close();
}catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn);//關閉數(shù)據庫連接
}
//返回更新記錄數(shù)
return count;
}
④編寫按標識符查詢用戶方法
@Override//按標識符查詢用戶方法
public User findById(int id) {
// 定義查詢用戶
User user = null;
//獲取數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
try {
//定義SQL字符串
String strSQL = "SELECT * FROM t_user WHERE id=?";
//創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
//設置占位符的值
pstmt.setInt(1,id);
//執(zhí)行查詢操作,返回結果集
ResultSet rs = pstmt.executeQuery();
//判斷結果集是否為空
if (rs.next()){
//創(chuàng)建用戶對象
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);//關閉數(shù)據庫連接
}
//返回查詢用戶
return user;
}
⑤編寫按用戶名查詢用戶的方法
@Override//按用戶名查詢用戶
public List<User> findByUsername(String username) {
//定義用戶列表
List<User> users = new ArrayList<>();
//獲取數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
try {
//定義SQL字符串
String strSQL = "SELECT * FROM t_user WHERE username=?";
//創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
//設置占位符的值
pstmt.setString(1,username);
//執(zhí)行查詢操作,返回結果集
ResultSet rs = pstmt.executeQuery();
//判斷結果集是否為空
while (rs.next()){
//創(chuàng)建用戶對象
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);//關閉數(shù)據庫連接
}
//返回用戶列表
return users;
}
⑥編寫查詢全部用戶方法
@Override//查詢所有用戶
public List<User> findAll() {
//定義用戶列表
List<User> users = new ArrayList<>();
//獲取數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
try {
//定義SQL字符串
String strSQL = "SELECT * FROM t_user";
//創(chuàng)建語句對象
Statement stmt = conn.createStatement();
//執(zhí)行查詢操作,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
//判斷結果集是否為空
while (rs.next()){
//創(chuàng)建用戶對象
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);//關閉數(shù)據庫連接
}
//返回用戶列表
return users;
}
⑦編寫登錄方法
@Override//登錄方法
public User login(String username, String password) {
//定義查詢用戶
User user = null;
//獲取數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
try {
//定義SQL字符串
String strSQL = "SELECT * FROM t_user WHERE username = ? and password = ?";
//創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
//設置占位符的值
pstmt.setString(1,username);
pstmt.setString(1,password);
//執(zhí)行查詢操作,返回結果集
ResultSet rs = pstmt.executeQuery();
//判斷結果集是否為空
if (rs.next()){
//創(chuàng)建用戶對象
user = new User();
//設置用戶對象屬性
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setTelephone(rs.getString("telephone"));
user.setRegisterTime(rs.getTimestamp("register_time"));
user.setPopedom(rs.getInt("popedom"));
}
//關閉預備語句對象
pstmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
ConnectionManager.closeConnection(conn);//關閉數(shù)據庫連接
}
//返回查詢用戶
return user;
}
(2)、對用戶數(shù)據訪問接口實現(xiàn)類做單元測試
- 于是項目里有了一個綠色的測試文件夾 -
test
- 在
test
文件夾里創(chuàng)建net.xyx.shop.dao.impl
包,在里面創(chuàng)建TestUserDaoImpl
①編寫測試登錄方法
- 給測試方法添加@Test注解,會報錯
- 添加單元測試JUnit項目,將光標移到@test注解上,按Alter+Enter鍵
- 單擊【Add ‘JUnit4’ to classpath】
- 單擊【OK】按鈕
- 運行testLogin()方法,查看效果
package net.xyx.shop.dao.impl;
import net.xyx.shop.bean.User;
import net.xyx.shop.dao.UserDao;
import org.junit.Test;
/**
* 測試用戶數(shù)據訪問接口實現(xiàn)類
*/
public class TestUserDaoImpl {
@Test
public void testLogin(){
String username = "admin";
String password = "12345";
//創(chuàng)建用戶數(shù)據訪問接口對象
UserDao userDao = new UserDaoImpl();//用父接口變量指向子類對象
//調用用戶數(shù)據訪問接口對象的登錄方法
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;
//創(chuàng)建用戶數(shù)據訪問接口對象
UserDao userDao = new UserDaoImpl();
//調用用戶數(shù)據訪問接口對昂的按標識符查詢用戶方法
User user = userDao.findById(id);
//判斷是否找到指定用戶
if (user != null){//找到
System.out.println(user);
}else{//未找到
System.out.println("編號為【" + id + "】的用戶為找到~");
}
- 運行
testFindById()
方法,查看結果
③編寫按用戶名查詢用戶方法
@Test //測試按用戶名查詢用戶
public void testFindByUsername(){
//定義用戶名變量
String username = "鄭曉紅";
//創(chuàng)建用戶數(shù)據訪問接口對象
UserDao userDao = new UserDaoImpl();
//調用用戶數(shù)據訪問接口對象的按用戶名查詢用戶方法
List<User> users = userDao.findByUsername(username);
//判斷是否找到
if(users.size() > 0){//找到
users.forEach(user -> System.out.println(user));
}else{//未找到
System.out.println("沒有找到名為[" + username + "]的用戶");
}
}
- 運行
testFindByUsername()
方法,查看結果 - 修改待查用戶名,在運行測試方法,查看結果
④編寫查詢全部用戶方法
- testFindAll()
@Test//測試查詢全部用戶
public void testFindAll(){
//創(chuàng)建用戶數(shù)據訪問接口對象
UserDao userDao=new UserDaoImpl();
//調用用戶數(shù)據訪問接口對象查詢全部用戶方法
List<User> users=userDao.findAll();
if(users.size()>0){
users.forEach(user -> System.out.println(user));
}else {
System.out.println("用戶表里面沒有記錄");
}
}
⑤編寫測試插入用戶方法
@Test //測試插入用戶
public void testInsert(){
//創(chuàng)建用戶對象
User user = new User();
//設置用戶對象屬性
user.setUsername("易烊千璽");
user.setPassword("1128");
user.setTelephone("12345678342");
user.setRegisterTime(new Date());
user.setPopedom(1);
//創(chuàng)建用戶數(shù)據訪問接口對象
UserDao userDao = new UserDaoImpl();
//調用用戶數(shù)據訪問接口對象的插入用戶方法
int count = userDao.insert(user);
//判斷是否成功插入用戶
if (count>0) {//成功
System.out.println("恭喜,插入用戶記錄成功~");
}else{//失敗
System.out.println("遺憾,插入用戶失敗~");
}
}
- 運行
testInsert()
方法,查看結果 - 在Navitcaat里查看用戶表
⑥編寫測試更新用戶方法
@Test//測試更新用戶
public void testUpdate(){
//創(chuàng)建用戶對象
User user = new User();
//設置用戶對象屬性
user.setId(5);
user.setUsername("劉艷芬");
user.setPassword("1343");
user.setTelephone("13728678342");
user.setRegisterTime(new Date());
user.setPopedom(1);
//創(chuàng)建用戶數(shù)據訪問接口對象
UserDao userDao = new UserDaoImpl();
//調用用戶數(shù)據訪問接口對象的更新用戶方法
int count = userDao.update(user);
//判斷是否成功更新用戶
if(count > 0){//成功
System.out.println("恭喜,更新用戶記錄成功~");
}else{
System.out.println("遺憾,更新用戶失敗~");
}
}
- 運行
testUpdate()
方法,查看結果
⑦編寫測試刪除用戶方法
@Test//測試刪除用戶
public void testDelete(){
//定義標識符變量
int id = 6;
//創(chuàng)建用戶數(shù)據訪問接口對象
UserDao userDao = new UserDaoImpl();
//調用用戶數(shù)據訪問接口對象的刪除用戶方法
int count = userDao.deleteById(id);
//判斷是否成功刪除用戶
if(count > 0){//成功
System.out.println("恭喜,刪除用戶成功~");
}else{
System.out.println("遺憾,刪除用戶失敗~");
}
}
- 運行
testDelete()
方法,查看結果 - 在Navicat里查看記錄,id為6的記錄沒有了
- 若想再次插入記錄下一次生成的是id為7的記錄
(3)、創(chuàng)建類別數(shù)據訪問接口實現(xiàn)類
- 在
net.xyx.shop.dao.impl
包里創(chuàng)建CategoryDaoImpl
類
①編寫插入類別方法
@Override // 插入類別
public int insert(Category category) {
// 定義插入記錄數(shù)
int count = 0;
// 獲得數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "INSERT INTO t_category (name) VALUES (?)";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 設置占位符的值
pstmt.setString(1, category.getName());
// 執(zhí)行更新操作,插入新錄
count = pstmt.executeUpdate();
// 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 關閉數(shù)據庫連接
}
// 返回插入記錄數(shù)
return count;
}
②編寫按標識符插入類別方法
@Override // 按標識符刪除類別
public int deleteById(int id) {
// 定義刪除記錄數(shù)
int count = 0;
// 獲得數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "DELETE FROM t_category WHERE id = ?";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 設置占位符的值
pstmt.setInt(1, id);
// 執(zhí)行更新操作,刪除記錄
count = pstmt.executeUpdate();
// 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 關閉數(shù)據庫連接
}
// 返回刪除記錄數(shù)
return count;
}
③編寫更新類別方法
@Override // 更新類別
public int update(Category category) {
// 定義更新記錄數(shù)
int count = 0;
// 獲得數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "UPDATE t_category SET name = ? WHERE id = ?";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 設置占位符的值
pstmt.setString(1, category.getName());
pstmt.setInt(2, category.getId());
// 執(zhí)行更新操作,更新記錄
count = pstmt.executeUpdate();
// 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 關閉數(shù)據庫連接
}
// 返回更新記錄數(shù)
return count;
}
④編寫按標識符查詢方法
@Override // 按標識符查詢類別
public Category findById(int id) {
// 聲明類別
Category category = null;
// 獲取數(shù)據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "SELECT * FROM t_category WHERE id = ?";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 設置占位符的值
pstmt.setInt(1, id);
// 執(zhí)行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); // 關閉數(shù)據庫連接
}
// 返回類別
return category;
}
⑤編寫查詢全部方法
@Override // 查詢全部類別
public List<Category> findAll() {
// 聲明類別列表
List<Category> categories = new ArrayList<Category>();
// 獲取數(shù)據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "SELECT * FROM t_category";
try {
// 創(chuàng)建語句對象
Statement stmt = conn.createStatement();
// 執(zhí)行SQL,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
// 遍歷結果集
while (rs.next()) {
// 創(chuàng)建類別實體
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); // 關閉數(shù)據庫連接
}
// 返回類別列表
return categories;
}
(4)、 對類別數(shù)據訪問接口對象做單元測試
- 在測試文件夾的
net.xyx.shop.dao.impl
包里創(chuàng)建TestCategoryDaoImpl
類
①編寫測試按標識符查詢類別方法
@Test // 測試按標識符查詢類別
public void testFindById() {
// 定義標識符變量
int id = 1;
// 創(chuàng)建類別數(shù)據訪問接口對象
CategoryDao categoryDao = new CategoryDaoImpl();
// 調用類別數(shù)據訪問接口對象的按標識符查詢類別方法
Category category = categoryDao.findById(id);
// 判斷是否找到指定類別
if (category != null) { // 找到
System.out.println(category);
} else { // 未找到
System.out.println("編號為[" + id + "]的類別未找到~");
}
}
②編寫測試查詢全部類別方法
@Test // 測試查詢全部類別
public void testFindAll() {
// 創(chuàng)建類別數(shù)據訪問接口對象
CategoryDao categoryDao = new CategoryDaoImpl();
// 調用類別數(shù)據訪問接口對象的查詢全部類別方法
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("廚房用具");
// 創(chuàng)建類別數(shù)據訪問接口對象
CategoryDao categoryDao = new CategoryDaoImpl();
// 調用類別數(shù)據訪問接口對象的插入類別方法
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("健身器械");
// 創(chuàng)建類別數(shù)據訪問接口對象
CategoryDao categoryDao = new CategoryDaoImpl();
// 調用類別數(shù)據訪問接口對象的更新類別方法
int count = categoryDao.update(category);
// 判斷類別是否更新成功
if (count > 0) {
System.out.println("恭喜,類別更新成功~");
} else {
System.out.println("遺憾,類別更新失敗~");
}
}
⑤編寫測試刪除類別方法
@Test // 測試按標識符刪除類別
public void testDeleteById() {
// 定義標識符變量
int id = 5;
// 創(chuàng)建類別數(shù)據訪問接口對象
CategoryDao categoryDao = new CategoryDaoImpl();
// 調用類別數(shù)據訪問接口對象的按標識符刪除類別方法
int count = categoryDao.deleteById(id);
// 判斷類別是否刪除成功
if (count > 0) {
System.out.println("恭喜,類別刪除成功~");
} else {
System.out.println("遺憾,類別刪除失敗~");
}
}
5、編寫商品數(shù)據訪問接口實現(xiàn)類
- 在
net.xyx.shop.dao.impl
包里創(chuàng)建ProductDaoImpl
類 - 實現(xiàn)
ProductDaoImpl
接口
①編寫插入商品方法
@Override
public int insert(Product product) {
int count = 0;
// 獲得數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "INSERT INTO t_product (name,price,add_time, category_id) VALUES (?,?,?,?)";
try {
//創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
//設置占位符的值
pstmt.setString(1,product.getName());
pstmt.setDouble(2,product.getPrice());
pstmt.setTimestamp(3,new Timestamp(product.getAddTime().getTime()));
pstmt.setInt(4,product.getCategotyId());
//執(zhí)行更新操作,返回插入記錄數(shù)
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) {
//定義刪除記錄數(shù)
int count = 0;
// 獲得數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "DELETE FROM t_product WHERE id = ?";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 設置占位符的值
pstmt.setInt(1, id);
// 執(zhí)行更新操作,刪除記錄
count = pstmt.executeUpdate();
// 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 關閉數(shù)據庫連接
}
//返回刪除記錄數(shù)
return count;
}
③編寫按標識符更新商品方法
@Override
public int update(Product product) {
// 定義更新記錄數(shù)
int count = 0;
// 獲得數(shù)據庫連接
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "UPDATE t_product SET name = ?,price = !,add_time = ?, category_id = ? WHERE id = ?";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 設置占位符的值
pstmt.setString(1, product.getName());
pstmt.setDouble(2, product.getPrice());
pstmt.setTimestamp(3,new Timestamp(product.getAddTime().getTime()));
pstmt.setInt(4, product.getCategotyId());
pstmt.setInt(5,product.getId());
// 執(zhí)行更新操作,更新記錄
count = pstmt.executeUpdate();
// 關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 關閉數(shù)據庫連接
}
// 返回更新記錄數(shù)
return count;
}
④編寫按標識符查詢商品方法
@Override
public Product findById(int id) {
// 聲明類別
Product product = null;
// 獲取數(shù)據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "SELECT * FROM t_product WHERE id = ?";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 設置占位符的值
pstmt.setInt(1, id);
// 執(zhí)行SQL查詢,返回結果集
ResultSet rs = pstmt.executeQuery();
// 判斷結果集是否有記錄
if (rs.next()) {
// 實例化商品
product = new Product();
// 利用當前記錄字段值去設置商品類別的屬性
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("privce"));
product.setAddTime(rs.getTimestamp("add_time"));
product.setCategotyId(rs.getInt("category_id"));
}
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 關閉數(shù)據庫連接
}
// 返回類別
return product;
}
⑤編寫按類別標識符查詢商品方法
@Override//按類別標識符查詢商品
public List<Product> findByCategoryId(int categoryId) {
//定義商品列表
List<Product> products = new ArrayList<>();
// 獲取數(shù)據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "SELECT * FROM t_product WHERE category_id = ?";
try {
// 創(chuàng)建預備語句對象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
//設置占位符的值
pstmt.setInt(1,categoryId);
// 執(zhí)行SQL查詢,返回結果集
ResultSet rs = pstmt.executeQuery();
//遍歷結果集
while (rs.next()){
// 實例化商品
Product product = new Product();
// 利用當前記錄字段值去設置商品類別的屬性
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("privce"));
product.setAddTime(rs.getTimestamp("add_time"));
product.setCategotyId(rs.getInt("category_id"));
//將商品對象添加到商品列表
products.add(product);
}
//關閉預備語句對象
pstmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn);
}
//返回商品列表
return products;
}
⑥編寫查詢全部商品方法
@Override//查詢全部商品方法
public List<Product> findAll() {
// 聲明類別列表
List<Product> products = new ArrayList<>();
// 獲取數(shù)據庫連接對象
Connection conn = ConnectionManager.getConnection();
// 定義SQL字符串
String strSQL = "SELECT * FROM t_category";
try {
// 創(chuàng)建語句對象
Statement stmt = conn.createStatement();
// 執(zhí)行SQL,返回結果集
ResultSet rs = stmt.executeQuery(strSQL);
// 遍歷結果集
while (rs.next()) {
// 創(chuàng)建商品實體
Product product = new Product();
// 設置實體屬性
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getDouble("price"));
product.setAddTime(rs.getTimestamp("add_time"));
product.setCategotyId(rs.getInt("category_id"));
// 將實體添加到類別列表
products.add(product);
}
// 關閉結果集
rs.close();
// 關閉語句對象
stmt.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
ConnectionManager.closeConnection(conn); // 關閉數(shù)據庫連接
}
// 返回類別列表
return products;
}
6、編寫測試商品數(shù)據訪問接口實現(xiàn)類
- 創(chuàng)建測試類
TestProductDaoImpl
,編寫測試方法testFindByCategoryId()
①編寫按標識符查詢商品方法
@Test
public void testFindById(){
int id = 1;
ProductDao productDao = new ProductDaoImpl();
//調用商品數(shù)據訪問接口對象的按標識符查詢商品方法
Product product = productDao.findById(id);
//判斷是否找到商品
if (product != null){
System.out.println(product);
}else{
System.out.println("編號為【" + id + "】的商品未找到~");
}
}
- 運行
testFindById()
方法,查看結果 - 修改標識符變量值,再運行
②編寫測試按類別標識符查詢商品方法
@Test//按類比標識符查詢商品
public void testFindByCategoryId(){
//定義類別標識符變量
int categoryId = 2;
//創(chuàng)建商品數(shù)據訪問接口對象
ProductDao productDao = new ProductDaoImpl();
//調用商品數(shù)據訪問接口對象的按類別標識符查詢商品方法
List<Product> products = productDao.findByCategoryId(categoryId);
//判斷指定類別里是否有商品
if (products.size() > 0){
products.forEach(product -> System.out.println(product));
}else{
System.out.println("類別編號為[" + categoryId + "]的商品未找到~");
}
}
- 運行
testFindByCategoryId()
查看結果
③編寫測試查詢全部商品方法
@Test//測試查詢全部商品
public void testFindAll(){
//創(chuàng)建類別數(shù)據訪問接口對象
ProductDao productDao = new ProductDaoImpl();
//調用類別數(shù)據訪問接口對象的按標識符查詢類別方法
List<Product>products = productDao.findAll();
if (products.size() >0){
products.forEach(product -> System.out.println(product));
}else{
System.out.println("商品表里沒有記錄~");
}
}
- 運行
testFindAll()
方法,查看結果
④編寫測試插入商品方法
@Test//測試插入商品
public void testInsert(){
//創(chuàng)建商品對象
Product product = new Product();
//設置商品對象屬性
product.setName("晨光簽字筆");
product.setPrice(3.0);
product.setAddTime(new Date());
product.setCategotyId(3);
//創(chuàng)建類別數(shù)據訪問接口對象
ProductDao productDao = new ProductDaoImpl();
//調用類別數(shù)據訪問接口對象的插入商品方法
int count = productDao.insert(product);
//判斷商品是否插入成功
if (count > 0){
System.out.println("恭喜,商品插入成功~");
}else{
System.out.println("抱歉,商品插入失敗~");
}
}
-
運行
testInsert()
方法,查看結果文章來源:http://www.zghlxwxcb.cn/news/detail-480054.html
-
在Navicat里面去查看
文章來源地址http://www.zghlxwxcb.cn/news/detail-480054.html
⑤編寫測試更新商品
@Test//測試更新商品
public void testUpdate(){
//定義類別對象
Product product = new Product();
//設置類別對象屬性
product.setId(5);
product.setName("萌萌噠薯片");
product.setPrice(10.0);
product.setAddTime(new Date());
product.setCategotyId(4);
//創(chuàng)建類別數(shù)據訪問接口對象
ProductDao productDao = new ProductDaoImpl();
//調用類別數(shù)據訪問接口對象的更新類別方法
int count = productDao.update(product);
if(count>0){
System.out.println("恭喜,商品更新成功~");
}else{
System.out.println("遺憾,商品更新失敗~");
}
}
⑥編寫測試刪除商品方法
@Test//測試刪除商品
public void testDeleteById(){
int id = 20;
ProductDao productDao = new ProductDaoImpl();
int count = productDao.deleteById(id);
if(count>0){
System.out.println("恭喜,商品刪除成功~");
}else{
System.out.println("遺憾,商品刪除失敗~");
}
}
- 查看運行結果
7、創(chuàng)建訂單數(shù)據訪問接口類OrderDaoImpl
到了這里,關于Java Web實訓項目:西蒙購物網的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!