配置好Mybaits之后,下面我们来为Dao层的UserDao来配置一个xml文件。

目前搭建的项目结构如下图:

上中篇(二)之UserDao的xml文件配置

写一下我对这个xml的理解(不一定正确):之前没有那个Mybatis的时候,我们需要写方法,连接数据库进行增删改查。当你要对某一个表进行操作时,要调用你之前写好的方法。(调用的话,就是传参,接受;可能传着传着就迷瞪了)。

有了这个xml的配置之后,我们就可以把SQL语句写在这个xml中,因为之前我们已经对Mybatis进行了配置,所以可以连接起来对数据库进行增删改查的操作。

总的来说就是,xml这个比之前那个更省事,更简单,更方面。现在我还不是很熟悉里面的具体过程,比如xml写好了之后,那它是在什么时候,是怎样被调用的呢?希望可以在接下来的学习中,能很好地解决这问题。

下面这段代码,UserDao.xml;

注意:空间命名的地方,要改成自己文件项目的空间名。代码片段中的 是我的空间名。得修改。

<mapper namespace="com.wy.dao.UserDao">
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 命名空间,xml文件和dao借口对接起来 -->
<mapper namespace="com.wy.dao.UserDao">
<!-- 查询列表 -->
<sql id="sqlWhere">
 <where>
		<if test="username!=null and username!=''">
			and username = #{username}<!-- 这种写法主动把第一个and去掉 -->
		</if>
		<if test="pwd!=null and pwd!=''">
			and pwd = #{pwd}
		</if>
		<!-- id与字符串的判断区别 -->
		<!-- id 是int 类型,直接不等于null就行,不用判断其是否为‘’ -->
		<if test="id !=null and id!=0"><!-- id!=0 -->
		and id = #{id}
		</if>
		<if test="realname !=null and realname !=''">
		and realname like CONCAT(concat('%',#{realname},'%'))<!--  -->
		</if>
		
	</where> 
</sql>
<!-- 查询列表 -->
<select id="list" parameterType="user" resultType="user">
	select * from user
	<include refid="sqlWhere"></include>
</select>

<!-- id不需要,自增 -->
<insert id="create" parameterType="user">
insert into user(username,pwd,realname) 
values(#{username},#{pwd},#{realname})
</insert>

<!-- 修改 -->
<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>

<delete id="delete" parameterType="integer">
delete from user where id = #{id}
</delete>

<select id = "updateBatch" resultType="user" parameterType="list">
update user set pwd = '123' where id in 
<foreach item = "item" index ="index" collection ="list" open="("
separator = ";" close=")">
#{item}
</foreach>
</select>
</mapper>

 

相关文章:

  • 2022-12-23
  • 2021-11-20
  • 2021-08-09
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
  • 2021-08-02
  • 2022-12-23
猜你喜欢
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-12
  • 2021-06-25
  • 2021-04-13
相关资源
相似解决方案