之前我整合了Spring和MyBatis这两个框架,不会的可以看我的这篇文章《MyBatis快速入门第七讲——MyBatis整合Spring》。本文我再来讲讲SpringMVC和MyBatis整合开发的方法,这样的话,Spring、MyBatis和SpringMVC三大框架的整合开发我们就学会了。这里我使用的Spring是Spring4.2.4这个版本(SpringMVC自然也是这个版本了),MyBatis是MyBatis3.2.7这个版本。在Spring、MyBatis以及SpringMVC这三大框架的整合开发过程中,不用我说,大家都应明白,控制层采用的是SpringMVC、持久层使用MyBatis来实现。
需求
实现商品查询列表,即从MySQL数据库表中查询出商品信息。
创建数据库表
为了实现这个需求,我们需要新建一个数据库,例如springmvc,然后将以下sql脚本文件(springmvc.sql)导入springmvc数据库中。
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50611
Source Host : localhost:3306
Source Database : springmvc
Target Server Type : MYSQL
Target Server Version : 50611
File Encoding : 65001
Date: 2016-05-09 19:45:13
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL COMMENT '商品名称',
`price` float(10,1) NOT NULL COMMENT '商品定价',
`detail` text COMMENT '商品描述',
`pic` varchar(64) DEFAULT NULL COMMENT '商品图片',
`createtime` datetime NOT NULL COMMENT '生产日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '台式机', '3000.0', '该电脑质量非常好!!!!', null, '2016-02-03 13:22:53');
INSERT INTO `items` VALUES ('2', '笔记本', '6000.0', '笔记本性能好,质量好!!!!!', null, '2015-02-09 13:22:57');
INSERT INTO `items` VALUES ('3', '背包', '200.0', '名牌背包,容量大质量好!!!!', null, '2015-02-06 13:23:02');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五', null, '2', null);
INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');
INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('24', '张三丰', null, '1'