目录:
1、使用注解的方式
2、输入输出参数的类型
输入参数类型
输出参数类型
3.mybatis中的动态SQL
1、使用注解的方式
public interface UserMapper {
@Select("select * from userInfo where id=#{id}")
@ResultType(UserInfo.class)
UserInfo getUserById(int id);
@Select("select * from userInfo")
//@ResultType(UserInfo.class) 这个注解不指定也可以
List<UserInfo> getAll();
@Select("select * from userInfo")
@Results({
@Result(id=true,column="id",property="id"),
@Result(column="userName",property="userName"),
@Result(column="password",property="password"),
@Result(column="note",property="note")
})
List<UserInfo> getAllUser();
@Insert("insert into userInfo (userName,password,note) values (#{userName},#{password},#{note} )" )
int add(UserInfo user);
//本例可以返回自增主键
@Insert("insert into userInfo (userName,password,note) values (#{userName},#{password},#{note} )" )
@Options(useGeneratedKeys = true,keyColumn = "id",keyProperty = "id")
int addAndReturnKey(UserInfo user);
@Delete("delete from userInfo where id =#{id}")
int delUser(int id);
@Update("update userInfo set userName=#{userName} ,password=#{password} , note =#{note} where id =#{id}" )
int updateUser(UserInfo user);
@Select("select * from userInfo where userName=#{a} and password=#{b} ")
UserInfo login(@Param("a")String userName, @Param("b") String password);
}
使用了注解方式,映射文件就可以不要
映射文件也可以和注解方式同时存在
2、输入输出参数的类型
(1)输入参数类型 parameterType
<insert id="add" parameterType="userInfo" >
insert into userInfo (userName,password,note) values (#{userName},#{password},#{note} )
</insert>
parameterType主要有以下几种
1)简单类型
2)pojo
3)包装过的pojo
//例
class School{
Student stu;
String address;
}
<insert id="add" parameterType="shcool" >
insert into student (stuName ... ) values (shcool.stu.studentName ...)
</insert>
//用school.stu取到Student的一个对象,然后接着.studentName就取到了stuName
4)hashMap
UserMapper接口中
public interface UserMapper{
UserInfo login(Map<String,String> params);
}
映射文件中UserMapper.xml
<select id="login" parameterType="map" resultType="UserInfo">
select * from userInfo where userName=#{key1} and password=#{key2}
</select>
测试文件中
public class Test{
public static void main(String[] args){
//以map的方式传参
Map<String,String> paramMap=new HashMap<>();
paramMap.put("Key1","赵强");
paramMap.put("key2","123456");
//调用登录方法
UserInfo user=userMapper.login(paramMap);
}
}
用这样的方式传参,适合参数个数较多,而且比较散乱的情况
另一种方式
附:也可以用 @Param 的方式对Mpper接口中的参数进行指定
UserInfo login(@Param("userName") String userName,@Param("password") String password);
然后在配置文件中:
<select id="login" resultType="UserInfo">
select * from userInfo where userName=#{userName} and password=#{password}
</select>
(2)输出参数类型
1)resultType
2)resultMap:它适合于我们要对查出来的结果集的映射进行细粒度的控制
<resultMap type="userInfo" id="userResultMap">
<id property="id" column="id" />
<result property="userName" column="uname"/>
<result property="password" column="pwd"/>
<result property="note" column="note"/>
</resultMap>
<select id="getUserById" resultMap="userResultMap">
select id, userName uname, password pwd ,note from userInfo where id = #{id}
</select>
3.mybatis中的动态SQL
mysql中实现动态SQL的主要元素有
if
choose (when otherwise)
trim
where
set
foreach
1) if 典型情况就是在多条件查询下
//例 接口中要加一个多条件查询的方法
UserMapper中
List<UserInfo> getSearchWhereList(UserInfo user);
映射文件中 (UserMapper.xml)
<select id="getSearchWhereList" parameterType="UserInfo" resultType="UserInfo">
select * from userinfo where 1=1
<if test="userName != null and userName !=''">
and userName=#{userName}
</if>
<if test="note != null and note !=''">
and note=#{note}
</if>
</select>
2) choose (OtherWise)
<?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">
<mapper namespace="com.beans.UserInfo">
<select id="chooseTest" parameterType="UserInfo" resultType="UserInfo">
select * from userinfo where 1=1
<choose>
<when test="userName!=null and userName !=''">
and userName=#{userName}
</when>
<when test="age!=null and age !=''">
and age=#{age}
</when>
<otherwise>
and note=#{note}
</otherwise>
</choose>
</select>
</mapper>
3) trim
prefix:前缀覆盖并增加其内容
suffix:后缀覆盖并增加其内容
prefixOverrides:前缀判断的条件
suffixOverrides:后缀判断的条件
<select id="xxx" ....>
select * from user
<trim prefix="WHERE" prefixoverride="AND |OR">
<if test="name != null and name.length()>0"> AND name=#{name}</if>
<if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>
</trim>
</select>
假如说name和gender的值都不为null的话打印的SQL为:select * from user where [ 这被替掉 ] name = 'xx' and gender = 'xx'
在 [ 这被替掉 ] 标记的地方是不存在第一个and的,上面两个属性的意思如下:
prefix:前缀
prefixoverride:去掉第一个and或者是or
4) where 的作用就是简化SQL中的where条件
select * from userinfo where 1=1 可以换成
select * from userinfo
<where>
................
</where>
其实就是用where标签对替换了where 1=1
SQL片段:尽量进行单表操作,在片段内尽量不要用where,可用性更高一点
片段的例子
一个典型的应用场合:多条件分页查询的时候
==查询数据
select * from userinfo where userName=xxx and password=xxx and age=xxx
select count(*) from userinfo where userName=xxx and password=xxx and age=xxx 我们发现查询条件符合的数据和条件符合的数据的总数需要的where条件是一样的,这时候我们就可以用SQL片段把where符合的条件封装起来
<?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">
<mapper namespace="com.beans.UserInfo">
<!--这个SQL片段可以在任意一个查询里面使用-->
<sql id="getUser_condation">
<if test="userName!=null and userName!='' ">
and userName =#{userName}
</if>
<if test="password!=null and password!='' ">
and password =#{password}
</if>
<if test="note!=null and note!='' ">
and note =#{note}
</if>
</sql>
<select id="getSearch" parameterType="UserInfo" resultType="UserInfo">
select * from userinfo
<where>
<include refid=""></include><!--引用一个片段-->
</where>
</select>
</mapper>
5)set
set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。
<update id="dynamicSetTest" parameterType="UserInfo">
update t_user
<set>
<if test="title != null">
title = #{title},
</if>
<if test="content != null">
content = #{content},
</if>
<if test="owner != null">
owner = #{owner}
</if>
</set>
where id = #{id}
</update>
有了set元素我们就可以动态的更新那些修改了的字段
6)foreach
下面的句子是想拼出select * from userinfo where id in (1,2,3,4)
<select id="getUserListByIds" resultType="userInfo" parameterType="list" >
select * from userInfo where id in
<foreach collection="list" item="item" separator="," open="(" close=")">
#{item}
</foreach>
</select>
小技巧 在配置sql语句的时候,直接用${value} ,传参的时候,直接把sql语句传过来
<select id="getUserListByIdList" resultType="userInfo" >
${value}
</select>
接口:
List<UserInfo> getUserListByIdList(String sql);
测试:
List<UserInfo> userList=userMapper.getUserListByIdList("select * from userinfo where id in (1,3,5,7,9) " );