您的位置:首页 > 其它

Mybatis中运用小技巧(一)

2016-05-19 21:39 399 查看
1、对于时间戳的处理

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

你的实体类.setTime(new Timestamp(System.currentTimeMillis()));<span style="white-space:pre">		</span>//我的实体类中对应属性名为time,<span style="font-family: Arial, Helvetica, sans-serif;">Timestamp具体类型为</span><span style="font-family: Arial, Helvetica, sans-serif;"></span>java.sql.Timestamp.Timestamp<span style="font-family: Arial, Helvetica, sans-serif;"></span>


如果在页面前台输出你希望可以输出的格式为“yyyy年MM月dd日HH:mm:ss”,那么你可以在你的实体类里专门写一个方法进行处理:

public String getNTime(){<span style="white-space:pre">		</span>//我将此方法取名为<span style="font-family: Arial, Helvetica, sans-serif;">getNTime</span>
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中声明的方法是:

<pre name="code" class="java">List<Microblog> <span style="font-family: Helvetica, Tahoma, Arial, sans-serif; line-height: 25.2px;">findByIds(String name, Long[] ids);</span>




需要转换成:

<span style="font-family: Helvetica, Tahoma, Arial, sans-serif; line-height: 25.2px;"></span><pre name="code" class="java" style="font-size: 14px; line-height: 25.2px;">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>


以上便是博主在mybatis中使用的方式,如果大家看了之后感觉博主哪边有错或者有疑问请在下方评论指出,博主将感激不尽!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: