Mybatis中运用小技巧(一)

1、对于时间戳的处理

如果你使用的是Mysql数据库的话,那么时间类型可以存储为timestamp类型,而你的项目中的实体类中相应属性的类型可以定义为java.util.Date类型。那么,存储时:

Object.setTime(new Timestamp(System.currentTimeMillis()));
//我的实体类中对应属性名为time,Timestamp具体类型为java.sql.Timestamp.Timestamp
如果在页面前台输出你希望可以输出的格式为“yyyy年MM月dd日HH:mm:ss”,那么你可以在你的实体类里专门写一个方法进行处理:
public String getNTime(){	//我将此方法取名为getNTime
    	DateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss"); 
    	String s = sdf.format(time);
    	return s;
}

2、如果传入mybatis的是一组数

这时可以分为两种情况:

一是传入是多个参数,如:

mapper.java中声明的方法是:

Follow selectByUserId1AndUserId2(Integer id, Integer id2);  
则在mapper.xml里的写法为:(以0、1来代替,适用于参数较少的情况)
<select id="selectByUserId1AndUserId2" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select 
    <include refid="Base_Column_List" />
    from follow
    where userId1 = #{0,jdbcType=INTEGER} and userId2 = #{1,jdbcType=INTEGER}
  </select>

二是传入的参数太多,需要包装为数组、List、Map的情况,如(此时多用于sql语句中出现in关键字):

mapper.java中声明的方法是:

List<Microblog> selectByIds(List<Integer> users); 
则在mapper.xml里的写法为:
<select id="selectByIds" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select 
    <include refid="Base_Column_List" />
    from microblog where userId in 
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
  		#{item}  
 	</foreach>
 	order by time desc
  </select>
这是list的情况,数组与之类似,只是需要将
collection="list"改为collection="array"

而如果是map情况,则是因为查询的参数有多个,如:

mapper.java中声明的方法是:

List<Microblog> findByIds(String name, Long[] ids);
需要转换成:
List<Microblog> findByIds(Map<String, Object> params);
Map<String, Object> params = new HashMap<String, Object>(2);
params.put("name", name);
params.put("ids", ids);
mapper.findByIdsMap(params);
则在mapper.xml里的写法为:
<select id="findByIdsMap" resultMap="BaseResultMap">  
 select  
 <include refid="Base_Column_List" />  
 from tabs where ID in  
 <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">  
  #{item}  
 </foreach>  
</select>  










猜你喜欢

转载自blog.csdn.net/u012843873/article/details/80298024