mybatis中常用方式或者mysql中得搜集
Mysql之CONTACT()函数
将查询结果拼接成一个字符串,返回结果为连接参数产生的字符串。如有任何一个参数为NULL ,则返回值为 NULL。
eg:select contact('11','22','33');
返回结果:112233

mybatis时间范围查询
<if test="excStartTime!=null and excStartTime!=''">
<![CDATA[ and DATE_FORMAT(dl.exc_start_time, '%Y-%m-%d')>= DATE_FORMAT(#{excStartTime}, '%Y-%m-%d') ]]>
</if>
<if test="excEndTime!=null and excEndTime!=''">
<![CDATA[ and DATE_FORMAT(dl.exc_end_time, '%Y-%m-%d') <= DATE_FORMAT(#{excEndTime}, '%Y-%m-%d') ]]>
</if>
大于号和小于号在mybatis中不起作用,所以要转换一下.
或者使用转义符.
<if test="excTimeLength != null">
and dl.exc_time_length >= #{excTimeLength,jdbcType=INTEGER}
</if>
<小于号 < > 大于号>

@Param注解的用法解析
一.xml形式
实例一 @Param注解单一属性
dao层示例
Public User selectUser(@param(“userName”) String name, @param(“userpassword”) String password);
xml映射对应示例
<select id=" selectUser" resultMap="BaseResultMap">
select * from user_user_t
where user_name = #{userName,jdbcType=VARCHAR} and user_password=#{userPassword,jdbcType=VARCHAR}
</select>
注意:采用#{}的方式把@Param注解括号内的参数进行引用(括号内参数对应的是形参如 userName对应的是name);
在不使用@Param注解的时候,函数的参数只能为一个,并且在查询语句取值时只能用#{},且其所属的类必须为Javabean,而使用@Param注解则可以使用多个参数,在查询语句中使用时可以使用#{}或者${}
@JsonIgnore注解
注解名称:@JsonIgnore
作用:在实体类向前台返回数据时用来忽略不想传递给前台的属性或接口。
Eg:User实体中会有字段password字段,当返回用户信息给前台的时候,当然是不希望将password值也一并返回。所以,这个时候可以在password属性上加上注解JsonIgnore或者,可以在User类上加上注解@JsonIgnoreProperties(value = "{password}")
List<BaseUser> getUsersByRoleIds(List<String> roleIds);

mybatis中的foreach
mapper.java
package com.hainei.mapper.wp.xcgl; import com.hainei.pojo.model.wp.xcgl.WpDzxjrw; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; @Mapper public interface WpDzxjrwMapper { int deleteByPrimaryKey(String id); List<WpDzxjrw> getListByAll(@Param(value = "list") List<Map> map, @Param(value = "listmes") List listmes, @Param(value = "columns") List<Map> columns, @Param(value = "userId") String userId); int insertSelective(WpDzxjrw record); WpDzxjrw selectByPrimaryKey(String id); int updateByPrimaryKeySelective(WpDzxjrw record); List<Map> getColumn(@Param(value = "tableName") String tableName, @Param(value = "dbName") String dbName); List<WpDzxjrw> selectBySelective(WpDzxjrw dzxjrw); WpDzxjrw getById(String id); List<WpDzxjrw> getByXjry(WpDzxjrw dzxjrw); List<WpDzxjrw> getListByStatus(); }
mapper
<?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.hainei.mapper.wp.xcgl.WpDzxjrwMapper"> <resultMap id="BaseResultMap" type="com.hainei.pojo.model.wp.xcgl.WpDzxjrw"> <id column="id" property="id" jdbcType="VARCHAR"/> <result column="rwmc" property="rwmc" jdbcType="VARCHAR"/> <result column="rwms" property="rwms" jdbcType="VARCHAR"/> <result column="rwzqks" property="rwzqks" jdbcType="TIMESTAMP"/> <result column="rwzqjs" property="rwzqjs" jdbcType="TIMESTAMP"/> <result column="rwpc" property="rwpc" jdbcType="VARCHAR"/> <result column="xjry" property="xjry" jdbcType="VARCHAR"/> <result column="sfcl" property="sfcl" jdbcType="INTEGER"/> <result column="cjr" property="cjr" jdbcType="VARCHAR"/> <result column="cjsj" property="cjsj" jdbcType="TIMESTAMP"/> <result column="xgr" property="xgr" jdbcType="VARCHAR"/> <result column="xgsj" property="xgsj" jdbcType="TIMESTAMP"/> <result column="wccs" property="wccs" jdbcType="INTEGER"/> <result column="remark2" property="remark2" jdbcType="VARCHAR"/> <result column="remark3" property="remark3" jdbcType="VARCHAR"/> <result column="pccs" property="pccs" jdbcType="INTEGER"/> <result column="sfwc" property="sfwc" jdbcType="INTEGER"/> <result column="delete_status" property="deleteStatus" jdbcType="INTEGER"/> <result column="szgw" property="szgw" jdbcType="VARCHAR" /> <result column="xjscqy" property="xjscqy" jdbcType="VARCHAR" /> <result column="cs" property="cs" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List"> id, rwmc, rwms, rwzqks, rwzqjs, rwpc, xjry, sfcl, cjr, cjsj, xgr, xgsj, wccs, remark2, remark3,pccs,sfwc, delete_status, szgw, xjscqy, cs </sql> <select id="getListByAll" resultMap="BaseResultMap"> select DISTINCT tn.* from wp_dzxjrw tn -- join base_data_table bdt on bdt.tableid=tn.id where 1=1 <foreach collection="list" item="item" index="index" open="" separator="" close=""> and tn.${item.key} like CONCAT("%",#{item.value},"%") </foreach> <!--<foreach collection="olists" item="oitem" index="index" open="and( 1!=1 " separator="" close=")">--> <!--or bdt.oid= #{oitem}--> <!--</foreach>--> <if test="listmes.size != 0"> <foreach collection="columns" item="item" index="index" open="and( 1!=1 " separator="" close=")"> <foreach collection="listmes" item="mes" index="index" open="" separator="" close=""> or tn.${item.COLUMN_NAME} like CONCAT("%",#{mes},"%") </foreach> </foreach> </if> AND judgeDataPermission(tn.id,#{userId},tn.cjr)=1 <!--<if test="olists.size == 0">--> <!--and bdt.oid= "11111111111111111111111111111111111111111"--> <!--</if>--> order by tn.cjsj desc </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String"> select <include refid="Base_Column_List"/> from wp_dzxjrw where id = #{id,jdbcType=VARCHAR} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.String"> delete from wp_dzxjrw where id = #{id,jdbcType=VARCHAR} </delete> <insert id="insertSelective" parameterType="com.hainei.pojo.model.wp.xcgl.WpDzxjrw" > insert into wp_dzxjrw <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="rwmc != null" > rwmc, </if> <if test="rwms != null" > rwms, </if> <if test="rwzqks != null" > rwzqks, </if> <if test="rwzqjs != null" > rwzqjs, </if> <if test="rwpc != null" > rwpc, </if> <if test="xjry != null" > xjry, </if> <if test="sfcl != null" > sfcl, </if> <if test="cjr != null" > cjr, </if> <if test="cjsj != null" > cjsj, </if> <if test="xgr != null" > xgr, </if> <if test="xgsj != null" > xgsj, </if> <if test="pccs != null" > pccs, </if> <if test="sfwc != null" > sfwc, </if> <if test="wccs != null" > wccs, </if> <if test="remark2 != null" > remark2, </if> <if test="remark3 != null" > remark3, </if> <if test="deleteStatus != null" > delete_status, </if> <if test="szgw != null" > szgw, </if> <if test="xjscqy != null" > xjscqy, </if> <if test="cs != null" > cs, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=VARCHAR}, </if> <if test="rwmc != null" > #{rwmc,jdbcType=VARCHAR}, </if> <if test="rwms != null" > #{rwms,jdbcType=VARCHAR}, </if> <if test="rwzqks != null" > #{rwzqks,jdbcType=TIMESTAMP}, </if> <if test="rwzqjs != null" > #{rwzqjs,jdbcType=TIMESTAMP}, </if> <if test="rwpc != null" > #{rwpc,jdbcType=VARCHAR}, </if> <if test="xjry != null" > #{xjry,jdbcType=VARCHAR}, </if> <if test="sfcl != null" > #{sfcl,jdbcType=INTEGER}, </if> <if test="cjr != null" > #{cjr,jdbcType=VARCHAR}, </if> <if test="cjsj != null" > #{cjsj,jdbcType=TIMESTAMP}, </if> <if test="xgr != null" > #{xgr,jdbcType=VARCHAR}, </if> <if test="xgsj != null" > #{xgsj,jdbcType=TIMESTAMP}, </if> <if test="pccs != null" > #{pccs,jdbcType=INTEGER}, </if> <if test="sfwc != null" > #{sfwc,jdbcType=INTEGER}, </if> <if test="wccs != null" > #{wccs,jdbcType=INTEGER}, </if> <if test="remark2 != null" > #{remark2,jdbcType=VARCHAR}, </if> <if test="remark3 != null" > #{remark3,jdbcType=VARCHAR}, </if> <if test="deleteStatus != null" > #{deleteStatus,jdbcType=INTEGER}, </if> <if test="szgw != null" > #{szgw,jdbcType=VARCHAR}, </if> <if test="xjscqy != null" > #{xjscqy,jdbcType=VARCHAR}, </if> <if test="cs != null" > #{cs,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.hainei.pojo.model.wp.xcgl.WpDzxjrw" > update wp_dzxjrw <set > <if test="rwmc != null" > rwmc = #{rwmc,jdbcType=VARCHAR}, </if> <if test="rwms != null" > rwms = #{rwms,jdbcType=VARCHAR}, </if> <if test="rwzqks != null" > rwzqks = #{rwzqks,jdbcType=TIMESTAMP}, </if> <if test="rwzqjs != null" > rwzqjs = #{rwzqjs,jdbcType=TIMESTAMP}, </if> <if test="rwpc != null" > rwpc = #{rwpc,jdbcType=VARCHAR}, </if> <if test="xjry != null" > xjry = #{xjry,jdbcType=VARCHAR}, </if> <if test="sfcl != null" > sfcl = #{sfcl,jdbcType=INTEGER}, </if> <if test="cjr != null" > cjr = #{cjr,jdbcType=VARCHAR}, </if> <if test="cjsj != null" > cjsj = #{cjsj,jdbcType=TIMESTAMP}, </if> <if test="xgr != null" > xgr = #{xgr,jdbcType=VARCHAR}, </if> <if test="xgsj != null" > xgsj = #{xgsj,jdbcType=TIMESTAMP}, </if> <if test="pccs != null" > pccs = #{pccs,jdbcType=INTEGER}, </if> <if test="sfwc != null" > sfwc = #{sfwc,jdbcType=INTEGER}, </if> <if test="wccs != null" > wccs = #{wccs,jdbcType=INTEGER}, </if> <if test="remark2 != null" > remark2 = #{remark2,jdbcType=VARCHAR}, </if> <if test="remark3 != null" > remark3 = #{remark3,jdbcType=VARCHAR}, </if> <if test="deleteStatus != null" > delete_status = #{deleteStatus,jdbcType=INTEGER}, </if> <if test="szgw != null" > szgw = #{szgw,jdbcType=VARCHAR}, </if> <if test="xjscqy != null" > xjscqy = #{xjscqy,jdbcType=VARCHAR}, </if> <if test="cs != null" > cs = #{cs,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=VARCHAR} </update> <select id="getColumn" resultType="java.util.Map"> select COLUMN_NAME from information_schema.COLUMNS where table_name = #{tableName} and table_schema = #{dbName} and COLUMN_NAME!="id" and COLUMN_NAME!="rwzqks" and COLUMN_NAME!="rwzqjs" and COLUMN_NAME!="cjsj" and COLUMN_NAME!="xgsj" and COLUMN_NAME!="pccs" and COLUMN_NAME!="sfwc" </select> <select id="selectBySelective" resultMap="BaseResultMap"> select DISTINCT d.id, d.rwmc, d.rwms, d.rwzqks, d.rwzqjs, d.rwpc, d.xjry,u.`name` xjryName,d.pccs,d.sfwc,d.cjsj, d.szgw, d.xjscqy,d.sfcl,d.cs from wp_dzxjrw d -- join base_data_table bdt on bdt.tableid=d.id LEFT JOIN base_user u on d.xjry = u.id where 1=1 <if test="szgw != null and szgw != ''"> AND d.szgw LIKE CONCAT(CONCAT('%',#{szgw,jdbcType=VARCHAR},'%')) </if> <if test="xjscqy != null and xjscqy != ''"> AND d.xjscqy LIKE CONCAT(CONCAT('%',#{xjscqy,jdbcType=VARCHAR},'%')) </if> <if test="rwmc != null and rwmc != ''"> AND d.rwmc LIKE CONCAT(CONCAT('%',#{rwmc,jdbcType=VARCHAR},'%')) </if> <if test="rwms != null and rwms != ''"> AND d.rwms LIKE CONCAT(CONCAT('%',#{rwms,jdbcType=VARCHAR},'%')) </if> <if test="rwzqks != null and rwzqjs != null"> AND d.rwzqks >= #{rwzqks,jdbcType=TIMESTAMP} AND rwzqjs <= #{rwzqjs,jdbcType=TIMESTAMP} </if> <if test="rwpc != null and rwpc != ''"> AND d.rwpc LIKE CONCAT(CONCAT('%',#{rwpc,jdbcType=VARCHAR},'%')) </if> <if test="cs != null "> AND d.cs LIKE CONCAT(CONCAT('%',#{cs,jdbcType=VARCHAR},'%')) </if> <if test="xjryName != null and xjryName != ''"> AND u.`name` LIKE CONCAT(CONCAT('%',#{xjryName,jdbcType=VARCHAR},'%')) </if> <if test="all != null and all != ''"> AND CONCAT(d.rwmc, d.rwms, d.rwpc, u.`name`, d.szgw, d.xjscqy) LIKE CONCAT(CONCAT('%',#{all},'%')) </if> <!--<if test="oidStr != null">--> <!--AND bdt.oid in (${oidStr})--> <!--</if>--> AND d.delete_status = 0 AND judgeDataPermission(d.id,#{cjr},d.cjr)=1 order by d.cjsj desc </select> <select id="getById" resultMap="BaseResultMap"> select d.id, d.rwmc, d.rwms, d.rwzqks, d.rwzqjs, d.rwpc, d.xjry,u.`name` xjryName,d.pccs,d.sfwc,d.cjsj, d.szgw, d.xjscqy,d.cs from wp_dzxjrw d LEFT JOIN base_user u on d.xjry = u.id where d.id = #{id,jdbcType=VARCHAR} </select> <select id="getByXjry" resultMap="BaseResultMap"> select <include refid="Base_Column_List"/> from wp_dzxjrw where 1=1 AND delete_status = 0 and DATE_FORMAT(rwzqks,"%Y-%m-%d")<=DATE_FORMAT(NOW(),"%Y-%m-%d") <if test="xjry != null"> AND xjry = #{xjry,jdbcType=VARCHAR} </if> <if test="sfcl == 0"> AND sfwc = 0 </if> <if test="sfcl == 1"> AND wccs != 0 </if> </select> <select id="getListByStatus" resultMap="BaseResultMap"> select * from wp_dzxjrw where 1=1 AND delete_status = 0 and sfwc = 0 and DATE_FORMAT(rwzqjs,"%Y-%m-%d")>=DATE_FORMAT(NOW(),"%Y-%m-%d") </select> </mapper>
foreach 属性介绍
foreach 用于迭代传入过来的参数。
它的属性介绍分别是
- collection:表示传入过来的参数的数据类型。该参数为必选。要做 foreach 的对象,作为入参时,List 对象默认用 list 代替作为键,数组对象有 array 代替作为键,Map 对象没有默认的键。当然在作为入参时可以使用 @Param(“keyName”) 来设置键,设置 keyName 后,list,array 将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:
如果 User 有属性 List ids。入参是 User 对象,那么这个 collection = “ids” 如果 User 有属性 Ids ids;其中 Ids 是个对象,Ids 有个属性 List id;入参是 User 对象,那么 collection = “ids.id”- 如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list
- 如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为 array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个 Map 了,当然单参数也可以封装成 map。
- item: 循环体中的具体对象。支持属性的点路径访问,如 item.age,item.info.details。具体说明:在 list 和数组中是其中的对象,在 map 中是 value,该参数为必选。(它是每一个元素进行迭代时的别名)
- index:在 list 和数组中,index 是元素的序号;在 map 中,index 是元素的 key。
- open:表示该语句以什么开始
- close:表示该语句以什么结束
- separator:表示在每次进行迭代之间以什么符号作为分隔符
介绍完属性之后,下面就进入实践。首先先来看一个简单到爆炸的表(表名:t_test_foreach)
单参数是 array 类型
测试类
// ids = {1,2,3}
public List<User> testFindByArray(int[] ids) throws Exception {
SqlSession sqlSession = getSession().openSession();
userList = sqlSession.selectList(NameSpace + ".findByArray", ids);
System.out.println(userList.toString());
sqlSession.close();
return userList;
}
mapper.xml
<!--这里的 item 值可以和传递过来的参数名不一样,在介绍属性的时候已经说过这是一个别名了。比如可以修改成如下代码:
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
#{id} <!--这里要和 item 值保持一致-->
</foreach>
-->
<select id="findByArray" resultType="com.test.foreach.User">
SELECT id,`name` FROM t_test_foreach WHERE id IN
<foreach collection="array" item="ids" index="index" open="(" close=")" separator=",">
#{ids}
</foreach>
</select>
输出结果
DEBUG - ==> Preparing: SELECT id,`name` FROM t_test_foreach WHERE id IN ( ? , ? , ? )
DEBUG - ==> Parameters: 1(Integer), 2(Integer), 3(Integer)
DEBUG - <== Total: 3
[User{name='n1', id='1'}, User{name='n2', id='2'}, User{name='n3', id='3'}]
单参数是 List 类型
测试类
// List 元素有 1,3,5
public List<User> testFindByList(List<Integer> ids) throws Exception {
SqlSession sqlSession = getSession().openSession();
userList = sqlSession.selectList(NameSpace + ".findByList", ids);
System.out.println(userList.toString());
sqlSession.close();
return userList;
}
mapper.xml
<select id="findByList" resultType="com.test.foreach.User">
SELECT id,`name` FROM t_test_foreach WHERE id IN
<foreach collection="list" item="ids" index="index" open="(" close=")" separator=",">
#{ids}
</foreach>
</select>
输出结果
DEBUG - ==> Preparing: SELECT id,`name` FROM t_test_foreach WHERE id IN ( ? , ? , ? )
DEBUG - ==> Parameters: 1(Integer), 3(Integer), 5(Integer)
DEBUG - <== Total: 3
[User{name='n1', id='1'}, User{name='n3', id='3'}, User{name='n5', id='5'}]
单参数是 Map 类型
测试类
// Map<String, Object> 中的元素有 int[] ids = {2, 4};map.put("ids", ids);
public List<User> testFindByMap(Map map) throws Exception {
SqlSession sqlSession = getSession().openSession();
System.out.println(map.toString());
List<Object> objects = sqlSession.selectList(NameSpace + ".findByMap", map);
System.out.println(objects.toString());
sqlSession.close();
return userList;
}
mapper.xml
<!--注意 collection 值是 ids,即要进行迭代的对象。觉得有点懵的伙伴可以回到最开始介绍 collection 属性那里看看,不要急-->
<select id="findByMap" resultType="com.test.foreach.User">
SELECT id,`name` FROM t_test_foreach WHERE id IN
<foreach collection="ids" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
输出结果
DEBUG - ==> Preparing: SELECT id,`name` FROM t_test_foreach WHERE id IN ( ? , ? )
DEBUG - ==> Parameters: 2(Integer), 4(Integer)
DEBUG - <== Total: 2
[User{name='n2', id='2'}, User{name='n4', id='4'}]
这种情况在传参数时,一定要改用 Map 方式
测试类
public void testUpdateByParams(int[] ids,String name) throws Exception {
SqlSession sqlSession = getSession().openSession();
Map<String,Object> map = new HashMap<String, Object>();
map.put("ids",ids); // ids = {1,2,4}
map.put("name",name);// name = "updated"
sqlSession.selectList(NameSpace + ".findByParams", map);
sqlSession.close();
}
mapper.xml
<select id="findByParams">
UPDATE t_test_foreach SET `name` = '#{name}' WHERE id IN
<foreach collection="ids" item="item" index="index" open="(" close=")" separator=",">
#{item}
</foreach>
</select>
输出结果
DEBUG - ==> Preparing: UPDATE t_test_foreach SET `name` = ? WHERE id IN ( ? , ? , ? )
DEBUG - ==> Parameters: updated(String), 1(Integer), 2(Integer), 4(Integer)
只查询当天的日期
<choose> <when test="txrqMax!=null and txrqMin!=null"> AND d.txrq >=#{txrqMin} AND d.txrq <=#{txrqMax} </when> <otherwise> <if test="txrqMin!=null"> AND txrq >= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE))*1000 AND txrq <=UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) + INTERVAL 1 DAY)*1000 </if> </otherwise> </choose>
String 类型的if else
<choose>
<when test="zt =='0'.toString()">
AND (zt='0' or zt='2')
</when>
<otherwise>
<if test="zt!=null and zt !=''">
AND zt=#{zt,jdbcType=VARCHAR}
</if>
</otherwise>
</choose>
1221
个人学习笔记,记录日常学习,便于查阅及加深,仅为方便个人使用。


浙公网安备 33010602011771号