3. Mybatis案例(返回结果)

数据库:

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:返回单一实体对象

  • Mapper 接口方法
User selectUserById(int id); 
  • Mapper 映射文件
<select id="selectUserById" parameterType="_int" resultMap="userMap">
        select * from `user` where id = #{id}
    </select>
  • 测试代码
User user = userMapper.selectUserById(2);
System.out.println(user);

案例2:返回集合实体对象

  • Mapper 接口方法
List<User> selectAllUser();
  • Mapper 映射文件
<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();
  • Mapper 映射文件
<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形式

  • Mapper 接口方法
Map<String,Object> selectOneMapUser(int id);
  • Mapper 映射文件
 <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();
}
  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我超爱写bug

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值