结果集配置
User selectUserById(int id);
<!--用于实体类属性和表中字段不一致时-->
<resultMap type="user" id="userMap">
<id column="id" property="id"/>
<result column="age" property="age"/>
<result column="user_name" property="userName"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
</resultMap>
<select id="selectUserById" parameterType="java.lang.Integer" resultMap="userMap" >
select * from t_user where id = #{id}
</select>
映射注解
@SelectProvider(value = BlogMapperProvide.class, method = "getPage")
List<Blog> getPage(@Param("title")String title, @Param("page")int page, @Param("size")int size);
/**
* 复杂sql语句的构建器
* 方式一:内部类
*/
class BlogMapperProvider {
public static String getPage(@Param("title")String title, @Param("page")int page, @Param("size")int size) {
return new SQL() {{
SELECT("*");
FROM("blog");
if(title != null) {
WHERE("title like concat(‘%‘, #{title} , ‘%‘)");
}
if(page > 0 && size > 0) {
LIMIT("#{page}, #{size}");
}
}}.toString();
}
}
/**
* 方式二:外部公开的类
*/
public class BlogMapperProvide {
public String getPage(@Param("title")String title, @Param("page")int page, @Param("size")int size) {
return new SQL() {{
SELECT("*");
FROM("blog");
if(title != null) {
WHERE("title like concat(‘%‘, #{title} , ‘%‘)");
}
if(page > 0 && size > 0) {
LIMIT("#{page}, #{size}");
}
}}.toString();
}
}
视图封装
/**
* 根据用户获取博客
* @param bup
* BlogUserParam类型是视图层vo中封装的数据类型
*/
List<BlogUserVO> getUserBlog(BlogUserParam bup) throws MapperException;
<!--根据用户获取博客 传入的参数类型和返回的参数类型 为视图层封装的类型-->
<select id="getUserBlog"
parameterType="top.yfly.blog.vo.BlogUserParam"
resultType="top.yfly.blog.vo.BlogUserVO">
select
<include refid="selbu"></include>
from t_blog b,
t_user_info ui, t_user u
where b.user_id = ui.user_id
and
b.user_id = u.id and ui.user_id = u.id
and b.user_id = #{userId}
<if test="blogType != null">
and b.blog_type = #{blogType}
</if>
<if test="blogTitle != null">
and b.blog_tile like concat(‘%‘,#{blogTitle} ,‘%‘)
</if>
<if test="inputTime != null">
order by b.create_time
</if>
<if test="praisedCount != null">
order by ui.praised_count desc
</if>
<if test="accessCount != null">
order by ui.access_count desc
</if>
<if test="pageNum !=null and pageSize != null">
limit #{pageNum}, #{pageSize}
</if>
</select>
mybatis入门