spring+springMVC+mybatis框架搭建(下篇)
一:项目连接数据库
数据库的搭建:新建数据库 " shop “ 脚本如下图所示:
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 50621
Source Host : localhost:3306
Source Database : shop
Target Server Type : MYSQL
Target Server Version : 50621
File Encoding : 65001
Date: 2019-03-12 17:17:55
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(50) DEFAULT NULL,
`pwd` varchar(50) DEFAULT NULL,
`realname` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zq', '111', '赚钱');
INSERT INTO `user` VALUES ('2', 'qq', '333', '争取');
二:连接数据库准备
在UserDao.xml中添加如下代码
<sql id="sqlWhere">
<where><!-- 这种写法会自动去掉第一个and -->
<if test="username!=null and username!=''">
and username = #{username}
</if>
<if test="pwd!=null and pwd!=''">
and pwd = #{pwd}
</if>
<!-- id与字符串判断区别 -->
<if test="id != null">
and id = #{id}
</if>
<if test="realname != null and realname != ''">
and realname like CONCAT(CONCAT('%',#{realname},'%'))<!-- '%'#{realname}'%' -->
</if>
</where>
</sql>
构建数据库代码查询语句:
<select id="list" parameterType="user" resultType="user">
select * from user
<include refid="sqlWhere"></include>
</select>
添加操作:
<update id="update" parameterType="user">
update user
<set>
<if test = "username != null and username != ''">
username = #{username},
</if>
<if test = "pwd != null and pwd != ''">
pwd = #{pwd},
</if>
<if test = "realname != null and realname != ''">
realname = #{realname},
</if>
</set>
where id = #{id}
</update>
三:测试一下。