在传统农产品交易模式中,信息不对称、客户服务响应滞后以及购买决策支持不足是长期存在的痛点。针对这些问题,我们设计并实现了一个集在线销售与智能交互于一体的垂直电商平台——"智慧农品通"。该平台采用成熟的SSM(Spring+SpringMVC+MyBatis)技术栈构建,通过智能问答技术显著提升了农产品交易的效率与用户体验。
系统架构与技术栈
系统采用经典的三层架构设计,Spring框架负责业务对象管理和事务控制,SpringMVC处理Web层请求路由与响应封装,MyBatis实现数据持久化操作。前端采用HTML+CSS+JavaScript技术组合,构建响应式用户界面。项目使用Maven进行依赖管理,MySQL作为数据存储引擎。
智能问答模块基于规则引擎与语义模板匹配技术构建,针对农产品特有的品类特性、种植方式、保鲜期等高频问题预置了专业的知识库。通过关键词提取和意图识别算法,系统能够快速理解用户查询意图,并通过RESTful API与前端进行实时交互。
// Spring MVC控制器配置示例
@Controller
@RequestMapping("/smartqa")
public class SmartQAController {
@Autowired
private QAService qaService;
@RequestMapping(value = "/query", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<QAResponse> handleQuery(@RequestBody QARequest request) {
try {
QAResponse response = qaService.processQuery(request.getQuestion());
return ResponseEntity.ok(response);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
数据库设计亮点分析
订单信息表(dingdanxinxi)设计
订单信息表的设计体现了电商系统对交易数据完整性和可追溯性的严格要求。表结构包含订单基本信息和状态管理字段,支持复杂的业务流程处理。
CREATE TABLE `dingdanxinxi` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`dingdanbianhao` varchar(50) NOT NULL COMMENT '订单编号',
`dingdanxinxi` text NOT NULL COMMENT '订单信息',
`zongjijine` decimal(18,2) NOT NULL COMMENT '总计金额',
`shouhuoren` varchar(50) NOT NULL COMMENT '收货人',
`dianhua` varchar(50) NOT NULL COMMENT '电话',
`dizhi` varchar(255) NOT NULL COMMENT '地址',
`beizhu` text NOT NULL COMMENT '备注',
`zhuangtai` varchar(255) NOT NULL COMMENT '状态',
`xiadanren` varchar(50) NOT NULL COMMENT '下单人',
`iszf` varchar(10) NOT NULL DEFAULT '否' COMMENT '是否支付',
`addtime` timestamp NOT NULL DEFAULT current_timestamp() COMMENT '添加时间',
`tuihuoreq` varchar(500) DEFAULT NULL COMMENT '退货请求',
`tuihuores` varchar(500) DEFAULT NULL COMMENT '退货响应',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COMMENT='订单信息'
设计亮点分析:
- 金额精度控制:使用decimal(18,2)类型存储金额,确保财务计算的精确性
- 状态管理灵活:zhuangtai字段采用varchar类型,支持多种订单状态的自定义扩展
- 退货流程完整:tuihuoreq和tuihuores字段分别记录退货请求和响应,形成完整的售后闭环
- 时间戳自动管理:addtime字段设置为timestamp类型并默认当前时间,确保数据时序性
商品信息表(projectxinxi)专业化扩展
商品信息表在传统电商商品模型基础上,增加了农产品特有的属性字段,体现了垂直领域的专业化设计。
CREATE TABLE `projectxinxi` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`projectbianhao` varchar(50) NOT NULL COMMENT '书籍编号',
`projectmingcheng` varchar(255) NOT NULL COMMENT '书籍名称',
`fenlei` int(10) unsigned NOT NULL COMMENT '分类',
`projecttupian` text NOT NULL COMMENT '书籍图片',
`xiaoshoujiage` decimal(18,2) NOT NULL COMMENT '销售价格',
`kucun` int(11) NOT NULL COMMENT '库存',
`zuozhe` varchar(50) NOT NULL COMMENT '作者',
`chubanshe` varchar(50) NOT NULL COMMENT '出版社',
`projectxiangqing` longtext NOT NULL COMMENT '书籍详情',
`tianjiaren` varchar(50) NOT NULL COMMENT '添加人',
`addtime` timestamp NOT NULL DEFAULT current_timestamp() COMMENT '添加时间',
`hit` int(11) NOT NULL DEFAULT 0 COMMENT '点击量',
`shifei` varchar(50) NOT NULL DEFAULT '未知' COMMENT '施肥',
`dayao` varchar(50) NOT NULL DEFAULT '未知' COMMENT '打药',
`dikuai` varchar(50) NOT NULL DEFAULT '未知' COMMENT '地块',
`jinxiao` varchar(50) NOT NULL DEFAULT '未知' COMMENT '禁销',
PRIMARY KEY (`id`),
KEY `projectxinxi_fenlei_index` (`fenlei`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COMMENT='书籍信息'
专业化字段设计:
- 农业生产溯源:shifei(施肥)、dayao(打药)字段记录种植过程,增强产品可信度
- 产地标识:dikuai(地块)字段明确农产品来源,满足消费者对原产地信息的需求
- 安全管控:jinxiao(禁销)字段实现商品上下架的灵活控制
- 分类索引优化:为fenlei字段建立索引,提升分类查询性能
购物车表(gouwuche)与订单明细关联设计
购物车表采用与订单明细相似的结构设计,便于实现购物车商品到订单的平滑转换。
CREATE TABLE `gouwuche` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`projectxinxiid` int(10) unsigned NOT NULL COMMENT '书籍信息id',
`projectbianhao` varchar(50) NOT NULL COMMENT '书籍编号',
`projectmingcheng` varchar(255) NOT NULL COMMENT '书籍名称',
`fenlei` int(10) unsigned NOT NULL COMMENT '分类',
`xiaoshoujiage` decimal(18,2) NOT NULL COMMENT '销售价格',
`goumaishuliang` int(11) NOT NULL COMMENT '购买数量',
`xiaoji` decimal(18,2) NOT NULL COMMENT '小计',
`goumairen` varchar(50) NOT NULL COMMENT '购买人',
`addtime` timestamp NOT NULL DEFAULT current_timestamp() COMMENT '添加时间',
PRIMARY KEY (`id`),
KEY `gouwuche_projectxinxiid_index` (`projectxinxiid`),
KEY `gouwuche_fenlei_index` (`fenlei`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COMMENT='购物车'
关联设计优势:
- 数据冗余合理:存储商品快照信息,避免商品信息变更对历史购物车数据的影响
- 计算字段优化:xiaoji字段预计算小计金额,减少实时计算开销
- 双索引策略:为商品ID和分类建立索引,支持多种查询场景
核心功能实现
智能商品管理子系统
商品管理模块采用面向接口的设计模式,支持农产品的全生命周期管理。管理员可以便捷地维护商品信息、库存状态以及农业生产相关属性。
// 商品服务接口定义
public interface ProductService {
ProductInfo getProductById(Integer id);
List<ProductInfo> getProductsByCategory(Integer categoryId);
boolean updateStock(Integer productId, Integer quantity);
boolean updateProductTraceability(Integer productId, String fertilizer, String pesticide);
}
// 商品管理控制器实现
@Controller
@RequestMapping("/admin/product")
public class ProductAdminController extends BaseController {
@Autowired
private ProductService productService;
@RequestMapping("/list")
public String productList(Model model) {
if (!checkLogin()) {
return showError("尚未登录", "./login.do");
}
String order = Request.get("order", "id");
String sort = Request.get("sort", "desc");
// 构建查询条件
Example example = new Example(Projectxinxi.class);
Example.Criteria criteria = example.createCriteria();
String where = " 1=1 ";
where += getProductWhere();
criteria.andCondition(where);
if (sort.equals("desc")) {
example.orderBy(order).desc();
} else {
example.orderBy(order).asc();
}
int page = request.getParameter("page") == null ? 1 : Integer.valueOf(request.getParameter("page"));
page = Math.max(1, page);
List<Projectxinxi> list = productService.selectPageExample(example, page, 15);
model.addAttribute("list", list);
model.addAttribute("orderby", order);
model.addAttribute("sort", sort);
return "admin/product_list";
}
private String getProductWhere() {
String where = " ";
if (!Request.get("projectmingcheng").equals("")) {
where += " AND projectmingcheng LIKE '%" + Request.get("projectmingcheng") + "%' ";
}
if (!Request.get("fenlei").equals("")) {
where += " AND fenlei = " + Request.get("fenlei");
}
return where;
}
}

智能购物车与订单处理
购物车模块实现了一站式购物体验,支持商品添加、数量修改、价格实时计算等功能。订单系统采用状态机模式管理订单生命周期。
// 购物车业务逻辑实现
@Service
public class ShoppingCartService {
@Autowired
private GouwucheMapper cartMapper;
@Autowired
private ProductMapper productMapper;
public boolean addToCart(Integer productId, Integer quantity, String username) {
// 检查商品库存
Projectxinxi product = productMapper.selectByPrimaryKey(productId);
if (product == null || product.getKucun() < quantity) {
return false;
}
// 检查是否已存在购物车记录
Example example = new Example(Gouwuche.class);
example.createCriteria()
.andEqualTo("projectxinxiid", productId)
.andEqualTo("goumairen", username);
List<Gouwuche> existingItems = cartMapper.selectByExample(example);
if (!existingItems.isEmpty()) {
// 更新现有记录
Gouwuche item = existingItems.get(0);
item.setGoumaishuliang(item.getGoumaishuliang() + quantity);
item.setXiaoji(item.getXiaoshoujiage().multiply(new BigDecimal(item.getGoumaishuliang())));
return cartMapper.updateByPrimaryKey(item) > 0;
} else {
// 新增购物车记录
Gouwuche newItem = new Gouwuche();
newItem.setProjectxinxiid(productId);
newItem.setProjectbianhao(product.getProjectbianhao());
newItem.setProjectmingcheng(product.getProjectmingcheng());
newItem.setFenlei(product.getFenlei());
newItem.setXiaoshoujiage(product.getXiaoshoujiage());
newItem.setGoumaishuliang(quantity);
newItem.setXiaoji(product.getXiaoshoujiage().multiply(new BigDecimal(quantity)));
newItem.setGoumairen(username);
return cartMapper.insert(newItem) > 0;
}
}
}

智能问答引擎实现
问答模块采用基于规则和模板匹配的混合策略,针对农产品领域的专业术语和常见问题进行了深度优化。
// 智能问答服务核心实现
@Service
public class QAServiceImpl implements QAService {
@Autowired
private KnowledgeBaseMapper knowledgeMapper;
@Autowired
private ProductMapper productMapper;
private static final Map<String, String> INTENT_KEYWORDS = new HashMap<>();
static {
// 初始化意图关键词映射
INTENT_KEYWORDS.put("价格", "PRICE_QUERY");
INTENT_KEYWORDS.put("多少钱", "PRICE_QUERY");
INTENT_KEYWORDS.put("库存", "STOCK_QUERY");
INTENT_KEYWORDS.put("有货", "STOCK_QUERY");
INTENT_KEYWORDS.put("产地", "ORIGIN_QUERY");
INTENT_KEYWORDS.put("来源", "ORIGIN_QUERY");
INTENT_KEYWORDS.put("有机", "CERTIFICATION_QUERY");
INTENT_KEYWORDS.put("认证", "CERTIFICATION_QUERY");
}
@Override
public QAResponse processQuery(String question) {
QAResponse response = new QAResponse();
// 意图识别
String intent = identifyIntent(question);
response.setIntent(intent);
// 实体提取
List<String> entities = extractEntities(question);
// 答案生成
String answer = generateAnswer(intent, entities, question);
response.setAnswer(answer);
return response;
}
private String identifyIntent(String question) {
for (Map.Entry<String, String> entry : INTENT_KEYWORDS.entrySet()) {
if (question.contains(entry.getKey())) {
return entry.getValue();
}
}
return "GENERAL_QUERY";
}
private String generateAnswer(String intent, List<String> entities, String question) {
switch (intent) {
case "PRICE_QUERY":
return handlePriceQuery(entities, question);
case "STOCK_QUERY":
return handleStockQuery(entities, question);
case "ORIGIN_QUERY":
return handleOriginQuery(entities, question);
default:
return handleGeneralQuery(question);
}
}
private String handlePriceQuery(List<String> entities, String question) {
// 实现价格查询逻辑
if (!entities.isEmpty()) {
Example example = new Example(Projectxinxi.class);
example.createCriteria().andLike("projectmingcheng", "%" + entities.get(0) + "%");
List<Projectxinxi> products = productMapper.selectByExample(example);
if (!products.isEmpty()) {
return products.get(0).getProjectmingcheng() + "的价格是:" +
products.get(0).getXiaoshoujiage() + "元";
}
}
return "请问您想了解哪个商品的价格?";
}
}

实体模型设计
系统采用JPA注解方式进行实体映射,确保数据对象与数据库表结构的精确对应。实体类设计遵循领域驱动设计原则,封装业务逻辑。
// 管理员实体类
@Table(name = "admins")
public class Admins implements Serializable {
@GeneratedValue(generator = "JDBC")
@Id
@Column(name = "id", insertable = false)
private Integer id;
@Column(name = "username")
private String username;
@Column(name = "pwd")
private String pwd;
@Column(name = "addtime")
private String addtime;
@Column(name = "role")
private String role;
@Column(name = "shopname")
private String shopname;
private static final long serialVersionUID = 1L;
// Getter和Setter方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? "" : username.trim();
}
// 其他getter/setter方法...
}
// 商品信息实体类
@Table(name = "projectxinxi")
public class Projectxinxi implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String projectbianhao;
private String projectmingcheng;
private Integer fenlei;
private String projecttupian;
private BigDecimal xiaoshoujiage;
private Integer kucun;
private String zuozhe;
private String chubanshe;
private String projectxiangqing;
private String tianjiaren;
private Timestamp addtime;
private Integer hit;
private String shifei;
private String dayao;
private String dikuai;
private String jinxiao;
// 关联属性
@Transient
private String fenleiName;
// Getter和Setter方法...
}
功能展望与优化方向
基于当前系统架构,未来可以从以下几个方向进行深度优化和功能扩展:
1. 引入Redis缓存层提升系统性能
在商品列表、分类信息等高频查询场景引入Redis缓存,显著降低数据库压力。实现缓存预热、多级缓存策略,提升系统响应速度。
// Redis缓存配置示例
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}