数据库:
drop database if exists mybatisdemo;
create database mybatisdemo;
use mybatisdemo;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', '张三', '2018-07-10', '1', '北京');
INSERT INTO `user` VALUES ('2', '李四', '2018-07-10', '0', '上海');
INSERT INTO `user` VALUES ('3', '王五', '2018-07-10', '1', '广州');
INSERT INTO `user` VALUES ('4', '王六', '2018-07-10', '1', '深圳');
INSERT INTO `user` VALUES ('5', '王八', '2018-07-10', '1', '上海');
案例1:返回单一实体对象
User selectUserById(int id);
<select id="selectUserById" parameterType="_int" resultMap="userMap">
select * from `user` where id = #{id}
</select>
User user = userMapper.selectUserById(2);
System.out.println(user);
案例2:返回集合实体对象
List<User> selectAllUser();
<select id="selectAllUser" resultMap="userMap">
select * from `user`
</select>
List<User> users = userMapper.selectAllUser();
for (User user : users) {
System.out.println(user);
}
案例3:返回Map的实体对象集合
- Mapper 接口方法
@MapKey(“id”)
Map<Integer,User> selectAllMapUser();
<select id="selectAllMapUser" resultMap="userMap">
select * from `user`
</select>
Map<Integer, User> userMap = userMapper.selectAllMapUser();
//遍历Map
Set<Integer> keys = userMap.keySet();
for (Integer key : keys) {
System.out.println(key + " --> " +userMap.get(key));
}
案例4:返回单个对象的Map形式
Map<String,Object> selectOneMapUser(int id);
<select id="selectOneMapUser" resultType="HashMap">
select * from `user` where id= #{id}
</select>
Map<String, Object> integerUserMap = userMapper.selectOneMapUser(1);
System.out.println(integerUserMap);
案例5:返回Map形式的数据行
- Mapper 接口方法
List< Map<String,Object> > selectAllMapCol(); - Mapper 映射文件
<select id="selectAllMapCol" resultType="map">
select * from `user`
</select>
List<Map<String, Object>> maps = userMapper.selectAllMapCol();
for (Map<String, Object> map : maps) {
Set<String> cols = map.keySet();
for (String col:cols) {
System.out.print(col+ ":"+map.get(col) +"\t");
}
System.out.println();
}