Mybatis中运用小技巧(一)

本文介绍了如何在Mysql数据库中处理时间戳,并提供了将时间戳格式化为特定日期格式的方法。此外,还详细说明了在MyBatis框架中如何正确地传递多个参数以及使用数组、List和Map作为参数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>  










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值