1. 程式人生 > >mybatis返回map操作

mybatis返回map操作

<?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.itheima.mybatis.mapper.UserMapper">
<!-- 根據使用者ID查詢使用者資訊 -->
<select id="findUserById" parameterType="int" resultType="User">
SELECT
* FROM USER WHERE id =#{id}
</select>

<!-- 新增使用者 -->
<insert id="insertUser" parameterType="com.itheima.mybatis.po.User">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT
LAST_INSERT_ID()
</selectKey>

INSERT INTO USER
(username,birthday,sex,address)
VALUES(#{username},#{birthday},#{sex},#{address})
</insert>

<!-- 定義sql片段 -->
<!-- sql片段內,可以定義sql語句中任何部分 -->
<!-- sql片段內,最好不用將where和select關鍵字宣告在內 -->
<sql id="whereClause">
<!-- if標籤:可以對輸入的引數進行判斷 -->
<!-- test:指定判斷表示式 -->
<if test="user != null">
<if test="user.username != null and user.username != ''">
AND username LIKE '%${user.username}%'
</if>
<if test="user.sex != null and user.sex != ''">
AND sex = #{user.sex}
</if>
</if>

<if test="idList != null">
<!-- AND id IN (#{id},#{id},#{id}) -->

<!-- collection:表示pojo中集合屬性的屬性名稱 -->
<!-- item:為遍歷出的結果宣告一個變數名稱 -->
<!-- open:遍歷開始時,需要拼接的字串 -->
<!-- close:遍歷結束時,需要拼接的字串 -->
<!-- separator:遍歷中間需要拼接的連線符 -->
AND id IN
<foreach collection="idList" item="id" open="(" close=")"
separator=",">
#{id}
</foreach>
</if>
</sql>

<!-- 綜合查詢,查詢使用者列表 -->
<select id="findUserList" parameterType="com.itheima.mybatis.po.UserQueryVO"
resultType="user">
SELECT * FROM user
<!-- where標籤:預設去掉後面第一個AND,如果沒有引數,則把自己幹掉 -->
<where>
<!-- 引入sql片段 -->
<include refid="whereClause" />
</where>
</select>

<!-- 綜合查詢使用者總數 -->
<select id="findUserCount" parameterType="com.itheima.mybatis.po.UserQueryVO"
resultType="int">
SELECT count(*) FROM user
<!-- where標籤:預設去掉後面第一個AND,如果沒有引數,則把自己幹掉 -->
<where>
<!-- 引入sql片段 -->
<include refid="whereClause" />
</where>
</select>

<!-- resultMap入門 -->
<!-- id標籤:專門為查詢結果中唯一列對映 -->
<!-- result標籤:對映查詢結果中的普通列 -->
<resultMap type="user" id="UserRstMap">
<id column="id_" property="id" />
<result column="username_" property="username" />
<result column="sex_" property="sex" />
</resultMap>

<select id="findUserRstMap" parameterType="int" resultMap="UserRstMap">
Select id id_,username username_,sex sex_ from user where id = #{id}
</select>
</mapper>

 

public interface UserMapper {
// 1、 根據使用者ID查詢使用者資訊
public User findUserById(int id) throws Exception;

// 3、 新增使用者
public void insertUser(User user) throws Exception;

//綜合查詢
public List<User> findUserList(UserQueryVO vo);

//綜合查詢使用者總數
public int findUserCount(UserQueryVO vo);

//resultMap入門
public User findUserRstMap(int id);
}