<!--namespace 非常重要:必须是 Mapper 类的全路径--> <mappernamespace="com.xtuer.mapper.DemoMapper"> <selectid="findDemoById"parameterType="int"resultType="Demo"> SELECT id, info FROM demo WHERE id = #{id} </select> </mapper>
Controller
1 2 3 4 5 6 7 8
@Autowired private DemoMapper demoMapper;
@GetMapping("/demos/{id}") @ResponseBody public Demo findDemoById(@PathVariableint id){ return demoMapper.findDemoById(id); }
<!-- [[1]] 简单的 JavaBean,直接使用 resultType: 数据库表的列与 JavaBean 的属性对应 --> <selectid="selectUserById"parameterType="int"resultType="com.tur.domain.User" > SELECT <includerefid="columns"/> FROM user WHERE id = #{id} </select>
<selectid="selectUsersByName"parameterType="string"resultType="com.tur.domain.User" > SELECT <includerefid="columns"/> FROM user WHERE name = #{name} </select>
<!-- [[2]] 可以使用 resultMap 映射自己的类: 例如多表查询时 --> <selectid="selectUserById"parameterType="int"resultMap="userResultMap" > SELECT <includerefid="columns"/> FROM user WHERE id = #{id} </select> <resultMapid="userResultMap"type="com.tur.domain.User" > <idproperty="id"column="id"/> <resultproperty="age"column="age"/> <resultproperty="name"column="name"/> </resultMap>
<!-- [[3]] 使用 resultMap 映射,属性是另一个类的对象: association --> <selectid="selectFullUserById"parameterType="int"resultMap="userAssociationResultMap" > SELECT user.id as id, <!-- 重命名列非常有用 --> user.age as age, user.name as name, ui.id as user_info_id, ui.user_id as user_info_user_id, ui.telephone as user_info_telephone, ui.address as user_info_address <!--FROM user, user_info ui--> FROM user INNER JOIN user_info ui ON user.id=ui.user_id WHERE user.id=#{id} <!--AND user.id=ui.user_id--> </select> <resultMapid="userAssociationResultMap"type="com.tur.domain.User" > <idproperty="id"column="id"/> <resultproperty="age"column="age"/> <resultproperty="name"column="name"/> <!--嵌套映射中还可以使用 resultMap: association, collection 还可以使用嵌套查询,但是会产生 N+1 问题,在大数量的数据库里会有很大的性能问题--> <!--<association property="userInfo" column="user_info_id" javaType="domain.UserInfo"> <id property="id" column="user_info_id"/> <result property="userId" column="user_info_user_id"/> <result property="telephone" column="user_info_telephone"/> <result property="address" column="user_info_address"/> </association>--> <!--association 是一对一关系,collection 是一对多关系--> <!--使用 columnPrefix 可以使 result map 重用--> <associationproperty="userInfo"column="user_info_id"columnPrefix="user_info_"resultMap="userInfoResultMap"/> </resultMap> <resultMapid="userInfoResultMap"type="com.tur.domain.UserInfo" > <idproperty="id"column="id"/> <resultproperty="userId"column="user_id"/> <resultproperty="telephone"column="telephone"/> <resultproperty="address"column="address"/> </resultMap>
<selectid="selectUsersWithName"parameterType="list"resultType="com.tur.domain.User" > SELECT <includerefid="columns"/> FROM user WHERE name in <foreachitem="item"index="index"open="("separator=","close=")"collection="list" > #{item} </foreach> </select> </mapper>