分享了以下tips:
一、事务管理
二、xml配置sql代码段
三、#和$的区别
四、注意对<、>做转义
五、依据字符串是否为空,动态组织sql语句
六、使用自定义的类型转换器
七、resultMap的复用
SqlSession session = getSqlSession();
int sqlResult = session.insert("insert a table", po);
int sqlResult = session.update("update b table", po);
//这时,前面的insert和update还没真正执行
session.commit();
//commit后,db才真正更新
session.close();
<sql id="getFeedBackList_fragment">
from t_comment where refer_type = #{type} and
refer_id = #{referId}
</sql>
<select id=‘getFeedBackList‘ parameterType=‘map‘ resultMap=‘feeback‘>
select id
<include refid="getFeedBackList_fragment"/>
order by
create_time desc
</select>
<configuration>
……
<typeHandlers>
<typeHandler handler="test.TimeTypeHandler"
javaType="Long" jdbcType="TIME" />
</typeHandlers>
……
</configuration>
package test;
public class TimeTypeHandler implements TypeHandler<Long>
{
private final String TIME_TYPE = "yyyy-MM-dd HH:mm:ss";
public long strToLongTime(String dateStr)
{
if (null == dateStr)
return 0L;
SimpleDateFormat sdf = new SimpleDateFormat(TIME_TYPE);
Date date = new Date();
try
{
date = sdf.parse(dateStr);
}
catch (ParseException e)
{
e.printStackTrace();
}
if (date == null)
return 0L;
System.out.println(date);
return date.getTime();
}
public Long getResult(ResultSet arg0, String arg1) throws SQLException
{
String datestr = arg0.getString(arg1);
return strToLongTime(datestr);
}
public Long getResult(ResultSet arg0, int arg1) throws SQLException
{
String datestr = arg0.getString(arg1);
return strToLongTime(datestr);
}
public Long getResult(CallableStatement arg0, int arg1) throws SQLException
{
String datestr = arg0.getString(arg1);
return strToLongTime(datestr);
}
public void setParameter(PreparedStatement arg0, int arg1, Long arg2, JdbcType arg3) throws SQLException
{
if (arg2 == null)
{
arg2 = 0L;
}
Date date = new Date(arg2);
SimpleDateFormat sdf = new SimpleDateFormat(TIME_TYPE);
String datetime = sdf.format(date);
arg0.setString(arg1, datetime);
}
}
<mapper namespace="xxxx">
……
//这里定义了ExpDownloadPo这个sql查询结果,要映射到java bean :test.ExpDownloadPo
<resultMap id="ExpDownloadPo" type="test.ExpDownloadPo">
<id property="id" column="id" />
//first_download_time这个数据,在赋值到firstDownloadTime时,要转转换,从jdbc的time型,转换成javaType的long型,具体怎么转换,因为前面第一点,定义了<typeHandlers><typeHandler handler="test.TimeTypeHandler" javaType="Long" jdbcType="TIME" /></typeHandlers>,因此会自动使用test.TimeTypeHandler这个转换器
<result property="firstDownloadTime" column="first_download_time" javaType="Long" jdbcType="TIME"/>
<result property="lastDownloadTime" column="last_download_time" javaType="Long" jdbcType="TIME"/>
</resultMap>
……
</mapper >
<mapper namespace="com.blog.test">
……
<resultMap id="testbean" ></resultMap>
</mapper>
<mapper namespace="B">
<select id="mysql" parameterType="map" resultMap="com.blog.test.testbean">
</mapper>
原文:http://blog.csdn.net/lizeyang/article/details/26081431