在上一篇,我们成功与数据库相连,并完成了查询操作,在这一篇,我们需要完善我们对数据库的操作。
1.打开UserDao.xml文件,并将查询语句进行完善
我们在mapper里写一个sql标签并在里面写上where判断语句
<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>
我们可以运行一下看看,我们的查询应该与上一篇的一致。
在浏览器里打开地址:/user/list.do?username=ls&pwd=333(问号后内数据根据数据库中的数据情况进行查询)
2.接着,我们来使id自增长
因为id不需要添加,当有一个数据添加时,id需要自己增长。
<insert id="create" parameterType="user">
insert into user(username,pwd,realname)
values(#{username},#{pwd},#{realname})
</insert>
3.我们进行对数据库的添加操作
<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>
4.对数据库进行删除操作
<delete id="delete" parameterType="integer">
delete from user where id = #{id}
</delete>
删除操作不像其他操作那样需要判断添加的数据是否合理,只需要提供id,就可以删除对应行的数据了。
5.批量操作
<update id="updateBatch" parameterType="List">
update user set pwd = '123' where id in
<foreach item="item" index="index" collection="list" open="("
separator="," close=")">
#{item}
</foreach>
</update>
以上,我们对数据库的管理就都做好了,下面我们在UserDao.java里进行配置。
public void create(User user);
public void update(User user);
public void delete(Integer id);
public void updateBatch(List<Integer> list);
这样就算彻底完成了,下面我们进行测试。
我们先只用添加操作来进行一下测试。
@ResponseBody
@RequestMapping("/create.do")
public boolean create(User user){
try{
userService.create(user);
}catch(Exception e){
System.out.println(e.getMessage());
return false;
}
return true;
}
我们在浏览器中输入地址:/user/create.do?username=to&pwd=123456&realname=haha
显示true应该就是添加成功了,现在我们到数据库中验证一下,记得要刷新表才能看到新的数据。
我们刚刚添加的数据已经在里面了,并且,id也自增长变成了4。
现在,我们的主要工作就已经全部完成了,但是我们还需要有一个文件,能够监控我们的操作是否有问题。
我们在src下建立一个文件,名字叫做:log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
这样,我们的任务就彻底完成了。