mybaits学习总结

来源:互联网 发布:js高级程序设计最新 编辑:程序博客网 时间:2024/05/16 01:50

1.总体配置文件configuration.xml

<typeAliases>
<package name="bean"/><!-- com.zrgk.entity -->
<!-- <package name="com.zrgk.entity />" -->
</typeAliases>

给bean起别名

<mappers><!-- 引入映射配置文件 -->
<mapper resource="bean/UserMapper.xml" />
</mappers>

resource="Mapper.xml所在的包名+Mapper的名字,包名之间用“/”隔开"

2.映射配置文件:UserMapper.xml

<mapper namespace="Mapper">

例如:<mapper namespace="bean.UserMapper">

resultType="" 是返回一条结果的的类型

例如:<select id="selectUserById" parameterType="int" resultType="bean.User">
select * from user where id=#{id}
</select>

条件查询:<select id="selectUserByCondition" parameterType="User" resultType="User">

select * from user where 1=1

<if test="name!=null and name!='' ">
and name like "%"#{name}"%"
</if>
<if test="age>0 ">
and age=#{age}
</if>
<if test="birthday!=null and birthday!='' ">
and birthday =#{birthday}
</if>

</select>


<select id="selectUserByCondition2" parameterType="bean.User" resultType="bean.User">

select * from user
<where>
<if test="name!=null and name!='' ">
name like "%"#{name}"%"
</if>
<if test="age>0 ">
and  age=#{age}
</if>
<if test="birthday!=null and birthday!='' ">
and birthday =#{birthday}
</if>
</where>

</select>
动态更新,参数有什么就会更新什么,传统的更新会把不设置值的内容更新为null
<update id="updateUserDyna" >
update user
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="age>0">
age=#{age},
</if>
<if test="birthday!=null">
birthday=#{birthday}
</if>
</set>
where id=#{id}
</update>


<!-- 动态查询foreach -->
<select id="dynaForeach" parameterType="java.util.List" resultType="bean.User">
select * from user where id in 
<foreach collection="list" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<!-- 动态查询foreach -->
<select id="dynaForeach2"  resultType="bean.User">
select * from user where id in 
<foreach collection="array" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<!-- 动态查询foreach -->
<select id="dynaForeach3" parameterType="java.util.Map" resultType="bean.User">
select * from user where name like "%"#{name}"%" and id in
<foreach collection="ids" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
</select>



0 0
原创粉丝点击