我们以浏览商品作为示例来展示操作流程:
1.执行excute()方法 :
package com.jerome.cmd.impl.goods;
import com.jerome.cmd.annotation.AdminCommand;
import com.jerome.cmd.annotation.CommandMeta;
import com.jerome.cmd.annotation.CustomerCommand;
import com.jerome.cmd.impl.AbstractCommand;
import com.jerome.cmd.impl.Subject;
import com.jerome.entity.Goods;
import java.util.List;
@CommandMeta(
name = "LLSP",
desc = "浏览商品",
group = "商品信息"
)
@AdminCommand
@CustomerCommand
public class GoodsBrowseCommand extends AbstractCommand {
@Override
public void excute(Subject subject) {
System.out.println("浏览商品");
//1.查询所有商品
List<Goods> goodsList = this.goodsService.queryAllGoods();
if (goodsList.isEmpty()) {
System.out.println("商品为空");
} else {
for (Goods goods : goodsList) {
System.out.println(goods);
}
}
}
}
2.调用Service层相应的方法:
package com.jerome.service;
import com.jerome.dao.GoodsDao;
import com.jerome.entity.Goods;
import java.util.List;
public class GoodsService {
public GoodsDao goodsDao;
public GoodsService() {
this.goodsDao = new GoodsDao();
}
public List<Goods> queryAllGoods() {
return this.goodsDao.queryAllGoods();
}
}
3.调用Dao层相应的方法:
package com.jerome.dao;
import com.jerome.entity.Goods;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class GoodsDao extends BaseDao {
public List<Goods> queryAllGoods() {
List<Goods> list = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = this.getConnection(true);
String sql = "select id,name,introduce,stock,unit,price,discount from goods;";//不要用*
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Goods goods = this.extractGoods(resultSet);
if (goods != null) {
list.add(goods);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeResource(resultSet, preparedStatement, connection);
}
return list;
}
//(解析货物)将从数据库中查询到的ResultSet进行解析,得到Goods对象
public Goods extractGoods(ResultSet resultSet) throws SQLException {
Goods goods = new Goods();
goods.setId(resultSet.getInt("id"));
goods.setName(resultSet.getString("name"));
goods.setIntroduce(resultSet.getString("introduce"));
goods.setStock(resultSet.getInt("stock"));
goods.setUnit(resultSet.getString("unit"));
goods.setPrice(resultSet.getInt("price"));
goods.setDiscount(resultSet.getInt("discount"));
return goods;
}
}
操作数据库结束之后,将结果返回到最一开始的excute()方法中。
由于我们进行的是查询货物的操作,所以我们将会得到一个货物的集合(List),通过遍历打印这个集合,我们就能得到对应的所有货物信息。
for (Goods goods : goodsList) {
System.out.println(goods);
}