标签 | 使用说明 | 举例 |
---|---|---|
select | id :唯一标识,和定义mybatis接口方法名一致。 | service层: Map<String, String> map = new HashMap<String, String>(); // 调用Dao层mybatis接口 Dao层: public List<String> selectData(Map<String> param); MyBatis层: <select id="selectData" parameterType="map" resultType="list"> |
parameterType :传入的参数类型,全路径名或别名。 例:com.test.poso.User或user | ||
resultType :返回值类型或别名,和定义mybatis接口方法返回类型一致。 | ||
resultMap:配置java对象属性与查询结果集中列名对应的关系。 | 可以参照:关于Mybatis的resultMap用法_ly741236987的博客-CSDN博客 | |
insert | id :和定义mybatis接口方法名一致。
resultType :返回值类型或别名,和定义mybatis接口方法返回类型一致。 | <insert id="insertUser" parameterType="User"> User(ID, NAME, AGE) values( #{ id }, #{name}, #{age}) |
update | <update id="updateUser" parameterType="User"> update User set NAME=#{name}, AGE=#{age} where ID=#{id} </update> | |
delete | <delete id="deleteUser" parameterType="User"> delete from User where ID = #{id} </delete> | |
if | test: 判断条件 | <select id="getUserName" parameterType="User" resultType="String"> NAME from User |
foreach | collection:collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合。 item :表示在迭代过程中每一个元素的别名。 index :表示在迭代过程中每次迭代到的位置(下标)。 open :前缀。 close :后缀。 separator :分隔符,表示迭代时每个元素之间以什么分隔。 | <select id="selectIn" resultType="String"> |
choose | 子标签 when中test:判断条件 | <select id="getName" parameterType="User" resultType="String"> SELECT NAME from USER WHERE 1=1 <where> <choose> <when test="ID!=null and ID!='' "> AND ID = #{id} </when> <otherwise> AND ID = "1" </otherwise> </choose> </where> </select> |
where | 相当于SQL的where关键字,不需要添加1=1, 如果name为空的情况,在拼接id条件时会自动剔除掉and(or) | <select id="getName" parameterType="User" resultType="String"> SELECT NAME from USER <where> <if test="name!=null and name!='' "> NAME LIKE CONCAT(CONCAT('%', #{name}),'%') </if> <if test="id!= null and id!= '' "> AND ID = #{id} </if> </where> </select> |
set | 如果age为空只更新name的情况,使用set标签会自动去除最后面逗号 | <update id="updateUser" parameterType="User"> UPDATE STUDENT <set> <if test="name!=null and name!='' "> NAME = #{name}, </if> <if test="age!=null and age!='' "> AGE = #{age} </if> </set> WHERE ID = #{id}; </update> |
sql | 多个sql查询了相同的字段,可以将相同的字段用<sql>的方式定义 | <sql id="Base_Column_List"> <select id="selectAll" resultType="User"> |
include | refid: 调用对应sql标签的id名称 | |
collection | 包在resultMap里作为结果集中某个属性,同结果集其他属性一起返回 | <resultMap id="userResultCollection" type="com.cloudwalk.shark.model.User"> <select id="selectRoles" resultType="com.cloudwalk.shark.model.Role">
|
<resultMap id="userResultCollection" type="com.cloudwalk.shark.model.User">
|
MyBatis 用法整理
最新推荐文章于 2023-05-17 08:38:47 发布