在Mybatis中,DAO接口文件与Mapper映射文件的接口方法是一致的
1.单个参数传递
UserDAO.java接口如下:
public interface UserDAO {
public User getUser(String UserName);
}
对应的UserDAOMapper.xml内容如下:
<?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.gszh.wmcp.project.weixinweb.dao.UserDAO">
<select id="getUser" resultType="com.gszh.wmcp.project.weixin.model.User">
SELECT * from T_User t
where UserName=#{UserName}
</select>
</mapper>
正常情况下,通过Spring的自动装载机制,调用UserDao.getUser接口方法时,Mybaits会自动关联到Mapper.xml对应的方法。
2.多个参数传递
如果getUser传递的是两个参数,则需要使用@Param注解,修改后UserDAO.java如下
public interface UserDAO {
public User getUser(@Param("UserName") String UserName,@Param("UID") String UID);
}
对应的UserDAOMapper.xml修改后内容如下:
<?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.gszh.wmcp.project.weixinweb.dao.UserDAO">
<select id="getUser" resultType="com.gszh.wmcp.project.weixin.model.User">
SELECT * from T_User t
where UserName=#{UserName} and UID=#{UID}
</select>
</mapper>
参数前缀@Param(“UserName”) 表示此参数将对应sql语句中的#{UserName},UID同理。
3.使用HashMap传递动态个数的参数
如果查询条件参数不固定,前端查询有可能仅使用1个参数,有可能同时使用3个参数,这时接口参数应该用HashMap的类型,动态获取参数。
DAO.java接口如下:
public interface GSUserBandingDAO {
public List<GSUserBanding> getList(HashMap<String, String> map);
public void deleteOne(String id);
}
方法getList中入参为hashMap,可接收不固定个数和参数
对应的Mapper.xml内容如下:
<select id="getList" resultMap="GSUserBanding" parameterType="java.util.HashMap">
SELECT * FROM V_gsuserbanding AS tm WHERE 1=1
<if test="NickName !=null and NickName!=''">
and NickName like "%"#{NickName}"%"
</if>
<if test="archNo !=null and archNo !=''">
and archNo like "%"#{archNo}"%"
</if>
<if test="UserName !=null and UserName !=''">
and UserName like "%"#{UserName}"%"
</if>
<if test="BeginTime !=null and BeginTime !=''">
and CreateTime <![CDATA[ >= ]]> #{BeginTime}
</if>
<if test="EndTime !=null and EndTime !=''">
and CreateTime <![CDATA[ <= ]]> #{EndTime}
</if>
<if test="start !=null and limit !=null">
limit ${start},${limit}
</if>
</select>
入参类型为Java.util.HashMap,对应接口文件的HashMap。
此xml文件中的sql查询语句,可以自动根据入参hashMap表中是否存在对应的字段参数,来选择查询条件执行,非常方便。