1.需要返回值为对象集合时,当集合返回值参数使用
mybatis的xml配置文件中配置设置
<resultMap id="user" type="com.demo.User" >
<result column="id" property="id" />
<result column="name" property="name" />
<result column="title" property="title" />
<result column="address" property="address" />
<result column="hobby" property="hobby" />
<result column="updateTime" property="updateTime" />
</resultMap>
<sql id="Base_Column_List">
t.id,
t.name,
t.title,
t.address,
t.hobby,
t.updateTime
</sql>
<select id="findAll" resultMap="user">
SELECT <include refid="Base_Column_List" />
FROM sys_user AS t
ORDER BY t.name, t.title, t.id ASC
</select>
Dao层的接收值方法,返回值使用List集合对象接口哦
public List<User> findAll();
返回结果展示:
[
{
"id":1,
"name":"张三",
"title":"我爱中国",
"hobby":"打网球",
"updateTime":"2021-06-18 10:00:00"
},
{
"id":2,
"name":"李四",
"title":"我爱祖国",
"hobby":"打游戏",
"updateTime":"2021-06-18 10:00:00"
}
]
2.出现一对多的情况,使用对应关系查找
<resultMap id="BaseResultMap" type="com.demo.entity.Teacher">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="address" jdbcType="VARCHAR" property="address"/>
<result column="hobby" jdbcType="VARCHAR" property="hobby"/>
<result column="updateTime" jdbcType="VARCHAR" property="updateTime"/>
<!--一对多-->
<collection property="stuList" ofType="com.demo.entity.Student" >
<id column="id" jdbcType="INTEGER" property="s_id" />
<result column="tId" jdbcType="INTEGER" property="tId" />
<result column="name" jdbcType="VARCHAR" property="s_name" />
<result column="address" jdbcType="VARCHAR" property="s_address"/>
<result column="hobby" jdbcType="TIMESTAMP" property="s_hobby"/>
<result column="updateTime" jdbcType="VARCHAR" property="updateTime"/>
</collection>
</resultMap>
<sql id="Base_Column_List">
t.id,
t.name,
t.address,
t.hobby,
t.updateTime,
s.id s_id,
s.tId ,
s.name s_name,
s.address s_address,
s.hobby s_hobby,
s.updateTime s_updateTime,
</sql>
<select id="selectTeacher" parameterType="com.demo.entity.Teacher"
resultMap="BaseResultMap">
select <include refid="Base_Column_List" />
from teacher t, student s where t.id = s.id
<if test="id != null">
and t.id = #{id}
</if>
</select>
Dao层接收mybatis的返回值
public List<Teacher> selectTeacherList(Teacher teacher);
返回结构展示:
[
{
"id":1,
"name":"张三",
"title":"我爱中国",
"hobby":"打网球",
"updateTime":"2021-06-18 10:00:00",
"students":
[
{
"id":1,
"name":"张三",
"title":"我爱中国",
"hobby":"打网球",
"updateTime":"2021-06-18 10:00:00"
},
{
"id":2,
"name":"李四",
"title":"我爱祖国",
"hobby":"打游戏",
"updateTime":"2021-06-18 10:00:00"
}
]
},
{
"id":2,
"name":"李四",
"title":"我爱祖国",
"hobby":"打游戏",
"updateTime":"2021-06-18 10:00:00",
"students":[]
}
]