MyBatis入门——MyBatis的基础操作(2)

目录

一、打印日志

二、参数传递

常见错误:使用对象接受

小结:

三、增(Insert)

返回主键

四、删(Delete)

五、改(Update)

六、查(Select)

1、起别名

2、结果映射

3、开启驼峰命名(推荐)


准备工作:
        存在的表如下:(表名:userInfo)

        代码如下:

        

        实体类UserInfo类:

@Data
public class UserInfo {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private Integer gender;
    private String phone;
    private Integer deleteFlag;
    private Date createTime;
    private Date updateTime;
}

        UserController类:

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/getUserAll")
    public List<UserInfo> getUserAll() {
        return userService.getUserAll();
    }
}

        UserServer类:

@Service
public class UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    public List<UserInfo> getUserAll() {
        return userInfoMapper.getUserInfoAll();
    }
}

        UserInfoMapper接口:

@Mapper
public interface UserInfoMapper {
    @Select("select * from userinfo")
    List<UserInfo> getUserInfoAll();
    
}

一、打印日志

        在MyBatis当中,我们可以借助日志,查看SQL语句的执行、执行传递的参数以及执行结果,只需在配置文件中进行配置即可,配置内容如下:

mybatis:
  configuration: # 配置打印 MyBatis⽇志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

        如果是application.properties,配置内容如下:

#指定mybatis输出⽇志的位置, 输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

        测试类代码如下:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void getUserInfoAll() {
        System.out.println(userInfoMapper.getUserInfoAll());
    }
}

        运行测试类,控制台比之前多出了一些内容,如下图:


二、参数传递

        需求:查找id=4的用户,对应的SQL就是:select * from userinfo where id=4;

        UserInfoMapper接口代码:

@Mapper
public interface UserInfoMapper {
    @Select("select * from userinfo where id=4")
    List<UserInfo> queryById();
}

        测试类代码如下:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryById() {
        System.out.println(userInfoMapper.queryById());
    }
}

        但代码也可以写成其他样子:传递参数的方式,代码如下:

@Mapper
public interface UserInfoMapper {
    @Select("select * from userinfo")
    List<UserInfo> getUserInfoAll();
    @Select("select * from userinfo where id=#{id}")
    List<UserInfo> queryById(Integer id);
}
@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryById() {
        System.out.println(userInfoMapper.queryById(4));
    }
}

        执行代码,结果如下:

        也可以通过@Param设置参数的别名,如果使用@Param设置别名,#{....}里的属性名必须和@Param设置的一样,代码如下:

@Mapper
public interface UserInfoMapper {
    @Select("select * from userinfo where id=#{userid}")
    List<UserInfo> queryById2(@Param("userid") Integer id);
}

        如果不设置别名,最好传递的参数要和SQL语句里的属性名一样。

常见错误:使用对象接受

        现在表的数据如下:

        我们查询gender=2的数据。

        UserInfoMapper接口代码如下:

@Mapper
public interface UserInfoMapper {
    @Select("select * from userinfo where gender=#{gender}")
    UserInfo queryById3(Integer gender);
}

        测试代码如下:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryById3() {
        userInfoMapper.queryById3(2);
    }
}

        运行测试代码,执行结果如下:

        现在更改一下数据,gender=2的数据只有一个了,如图:

        在运行测试代码,没有报错,结果如下:

小结:

        对于只有一个返回结果,可以使用对象或集合接收对于有多个返回结果,只能使用集合接收


三、增(Insert)

        SQL语句:

insert into userinfo(username, password, age, gender, phone) values("zhaoliu","zhaoliu",19,1,"18700001234");

        UserInfoMapper接口代码如下:

没有使用@Param注解:

@Mapper
public interface UserInfoMapper {
    @Insert("insert into userinfo(username, password, age, gender) " +
            "values(#{username}, #{password}, #{age}, #{gender})")
    Integer insert(UserInfo userInfo);
}

使用@Param注解:

@Mapper
public interface UserInfoMapper {
    @Insert("insert into userinfo(username, password, age, gender) " +
            "values(#{userInfo.username}, #{userInfo.password}, #{userInfo.age}, #{userInfo.gender})")
    Integer insert(@Param("userInfo") UserInfo userInfo);
}

        测试类代码如下:

@SpringBootTest
class UserInfoMapperTest {
    @Test
    void insert() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("zhaoliu");
        userInfo.setPassword("123456");
        userInfo.setAge(66);
        userInfo.setGender(2);
        userInfoMapper.insert(userInfo);
    }
}

        运行测试类,控制台打印内容如下:

        查看userInfo表

        确实多了一行,id没衔接上是因为之前我测试了一下,添加了几行数据,后面又删除了。

返回主键

        想要添加主键,再加个@Options注解就好了。

        UserInfoMapper接口代码:

@Mapper
public interface UserInfoMapper {
    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into userinfo(username, password, age, gender) " +
            "values(#{username}, #{password}, #{age}, #{gender})")
    Integer insert2(UserInfo userInfo);
}

        注解内的属性解释:

useGeneratedKeys这会令MyBatis使用JDBC的getGeneratedKeys方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的自动递增字段),默认值:false

keyProperty指定能够唯一识别对象的属性,MyBatis会使用getGeneratedKeys的返回值或Insert语句的selectKey子元素设置它的值默认值:未设置(unset)

        测试类代码:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    @Test
    void insert2() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername("zhaoliu");
        userInfo.setPassword("123456");
        userInfo.setAge(66);
        userInfo.setGender(2);
        Integer count = userInfoMapper.insert2(userInfo);
        System.out.println("添加数据数:" + count + "数据ID:" + userInfo.getId());
    }
}

        运行测试类,运行结果如下:

注意设置 useGeneratedKeys=true之后,方法返回值依然是受影响的行数,自增id会设置在上述keyProperty指定的属性中


四、删(Delete)

        SQL:

delete from userinfo where id = 11

        UserInfoMapper接口代码:

@Mapper
public interface UserInfoMapper {
    @Delete("delete from userinfo where id = #{id}")
    Integer delete(Integer id);
}

        测试类代码:

@SpringBootTest
class UserInfoMapperTest {
    @Test
    void delete() {
        System.out.println(userInfoMapper.delete(11));
    }
}

        运行测试类前:

        运行测试类,结果如下:

        可以看到,id为11的数据被删除了。


五、改(Update)

        USerInfoMapper接口类代码:

@Mapper
public interface UserInfoMapper {
    @Update("update userinfo set username = #{username} where id = #{id}")
    Integer upadate(String username ,Integer id);
}

        测试类代码:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void upadate() {
        userInfoMapper.upadate("zhouba", 10);
    }
}

        运行测试类前表的数据:

        运行测试类,结果如下:

        可以看到,修改成功了。


六、查(Select)

        USerInfoMapper接口代码:

@Mapper
public interface UserInfoMapper {
    @Select("select id, username, `password`, age, gender, phone, delete_flag, create_time, update_time from userinfo")
    List<UserInfo> queryAllUser();
}

        测试类代码:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryAllUser() {
        System.out.println(userInfoMapper.queryAllUser());
    }
}

        运行测试类代码,结果如下:

        可以看到,有三个属性都是没有值的,为null原因数据库表的列名和实体类的属性名不一样,如图:

        也就是说自动映射查询结果时,MyBatis会获取结果中返回的列名并在Java类中查找相同名字的属性(忽略大小写)这意味着如果发现 ID列 和 id属性 对应时,MyBatis会把 ID列 的值赋给id属性

        因为数据库里面的表的列名 命名规范 和 Java的属性命名规范不一样,从而导致双方给同一个对象命名的名称不同,也就不能自动给它映射了解决办法有三种1、起别名  2、结果映射  3、开启驼峰命名

1、起别名

        USerInfoMapper接口类:

@Mapper
public interface UserInfoMapper {
    @Select("select id, username, `password`, age, gender, phone, " +
            "delete_flag as deleteFlag, create_time as createTime, update_time as updateTime from userinfo")
    List<UserInfo> queryAllUser2();
}

        测试类:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryAllUser2() {
        System.out.println(userInfoMapper.queryAllUser2());
    }
}

        运行测试类代码,结果如下:

        可以看到,现在的deleteFlag、createTime、updateTime 都不是null了。

2、结果映射

        使用@Results和@Result注解,USerInfoMapper类代码如下:

@Mapper
public interface UserInfoMapper {
    @Results({
            @Result(column = "delete_flag", property = "deleteFlag"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime")
    })
    @Select("select id, username, `password`, age, gender, phone, delete_flag, create_time, update_time from userinfo")
    List<UserInfo> queryAllUser3();
}

        测试类代码如下:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryAllUser3() {
        System.out.println(userInfoMapper.queryAllUser3());
    }
}

        运行测试类代码,结果如下:

        如果希望其他SQL也可以使用该映射就给@Results注释多加个id属性,其他SQL想使用,就加@ResultMap注解使用,代码如下:

@Mapper
public interface UserInfoMapper {
    @Results(id = "resultMap" , value = {
            @Result(column = "delete_flag", property = "deleteFlag"),
            @Result(column = "create_time", property = "createTime"),
            @Result(column = "update_time", property = "updateTime")
    })
    @Select("select id, username, `password`, age, gender, phone, delete_flag, create_time, update_time from userinfo")
    List<UserInfo> queryAllUser4();

    @ResultMap(value = "resultMap")
    @Select("select id, username, `password`, age, gender, phone, delete_flag, create_time, update_time from userinfo")
    List<UserInfo> queryAllUser5();
}

        使用id属性给该Results定义别名,使用@ResultMap注释来复用其他定义的ResultMap。如图:

3、开启驼峰命名(推荐)

        通常数据库列使用蛇形命名发进行命名(下划线分割各个单词),而Java属性一般遵循驼峰命名法约定为了在这两种命名方式之间启用自动映射,需要将 mapUnderscoreToCamelCase  设置为true。xml文件内容如下:

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #配置打印 MyBatis⽇志
    map-underscore-to-camel-case: true  #自动驼峰转换

        驼峰命名规则abc_xyz => abcXyz表中字段名abc_xyz类中属性名abcXyz

        现在重新使用下面代码测试,USerInfoMapper接口代码如下:

@Mapper
public interface UserInfoMapper {
    @Select("select id, username, password, age, gender, phone, delete_flag, create_time, update_time from userinfo")
    List<UserInfo> queryAllUser();
}

        测试类代码:

@SpringBootTest
class UserInfoMapperTest {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Test
    void queryAllUser() {
        System.out.println(userInfoMapper.queryAllUser());
    }
}

        运行测试类代码,结果如下:

        可以看到,deleteFlag、createTime、updateTime这三个属性的值不为null全都被赋值了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/659068.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【wiki知识库】03.前后端的初步交互(展现所有的电子书)

&#x1f4dd;个人主页&#xff1a;哈__ 期待您的关注 目录 一、&#x1f525;今日目标 二、&#x1f4c2;前端配置文件补充 三、&#x1f30f;前端Vue的改造 四、&#x1f4a1;总结 一、&#x1f525;今日目标 在上一篇文章当中&#xff0c;我已带大家把后端的一些基本工…

最新微信发卡小程序 发卡网卡密系统流支持量主

2024.4更新 1.修复分类介绍报错 2.修改前端UI 3.增加插屏弹出广告 4.禁止PC端使用(PC端小程序没有广告) 免费下载&#xff1a;发卡小程序 卡密系统流支持量主 多种卡密领取模式【亲测】_麦田吧 前端演示地址&#xff1a;扫码查看 源码功能&#xff1a; 小程序系统/多种卡密领…

vscode远程登录阿里云服务器【使用密钥方式--后期无需再进行密码登录】【外包需要密码】

1&#xff1a;windows主机上生成【私钥】【公钥】 1.1生成公钥时不设置额外密码 1.2生成公钥时设置额外密码【给外包人员使用的方法】 2&#xff1a;在linux服务器中添加【公钥】 3&#xff1a;本地vscode连接linux服务器的配置 操作流程如下 1.1本地终端中【生成免密登录…

14.微信小程序之地理定位功能

目录 1.地理定位介绍 1.1 申请开通 1.2 使用方法 2.拒绝授权后的解决方案 3.开通腾讯位置服务 4.LBS 逆地址解析 1.地理定位介绍 小程序地理定位是指通过小程序开发平台提供的 API&#xff0c;来获取用户的地理位置信息。用户在使用小程序时&#xff0c;可以授权小程序获…

MySQL 数据表的基本操作

文章目录 【 1. MySQL 创建数据表 】【 2. MySQL 查看表 】2.1 DESCRIBE/DESC 以表格的形式展示表2.2 SHOW CREATE TABLE 以SQL语句的形式展示表 【 3. 修改数据表 】3.1 修改表名3.2 修改表字符集3.3 添加字段在末尾添加字段在开头添加字段在中间添加字段 3.3 修改/删除字段修…

Nginx的配置与调试

目录 1、安装Nginx 2、Nginx的配置文件结构 2.1 Nginx的全局配置 2.2 HTTP服务器配置 2.3 HttpGzip模块配置 2.4 负载均衡配置 2.5 server虚拟主机配置 2.6 location URL匹配配置 2.7 StubStatus模块配置 1、安装Nginx 在安装Nginx之前&#xff0c;需确保系统已经安装…

【计算机网络】P1 计算机网络概念、组成、功能、分类、标准化工作以及性能评估指标

目录 1 什么是计算机网络2 计算机网络的组成2.1 组成部分上2.2 工作方式上2.3 功能组成上 3 计算机网络的功能3.1 数据通信3.2 资源共享3.3 分布式处理3.4 提高可靠性3.5 负载均衡 4 计算机网络的分类4.1 按分布范围分类4.2 按传输技术分类4.3 按照拓扑结构分类4.4 按使用者分类…

vue项目中使用json编辑器

实现效果&#xff1a; 借助插件json-editor-vue3实现效果如图一&#xff0c;如果嫌丑可以通过类名改一下样式如图二。 实现过程&#xff1a; 安装插件&#xff1a;npm install json-editor-vue3 文档链接&#xff1a;GitCode - 开发者的代码家园 <script setup name&quo…

一次收获颇丰的Google漏洞挖掘旅程

本文由安全专家Henry N. Caga于2024年03月23日发表在InfoSecWrite-ups网站&#xff0c;本文记录了Henry N. Caga的一次漏洞挖掘过程&#xff0c;此次漏洞挖掘的成果得到了Google官方认可&#xff0c;拿到了4133.70美元的漏洞奖金&#xff0c;并让他成功进入了Google名人堂。本文…

C++第二十一弹---vector深度剖析及模拟实现(上)

✨个人主页&#xff1a; 熬夜学编程的小林 &#x1f497;系列专栏&#xff1a; 【C语言详解】 【数据结构详解】【C详解】 目录 1、基本结构 2、默认成员函数 2.1、构造函数 2.2、析构函数 2.3、拷贝构造函数 2.3、赋值操作符重载 3、数据访问 4、迭代器获取 总结 …

08.tomcat多实例

在加两个tomcat实例 [rootweb01 ~]# ll apache-tomcat-8.0.27.tar.gz -rw-r--r-- 1 root root 9128610 10月 5 2015 apache-tomcat-8.0.27.tar.gz [rootweb01 ~]# tar xf apache-tomcat-8.0.27.tar.gz [rootweb01 ~]# cp -a apache-tomcat-8.0.27 tomcat_8081 [rootweb01 ~…

基于单片机的操作平台数据采集网关设计与实现

摘  要&#xff1a; 由于传统网关无法实现数据实时交换&#xff0c;数据传输速率较低&#xff0c;为此提出基于单片机的操作平台数据采集网关设计与实现研究。首先&#xff0c;结合单片机具有的显著优势对网关结构选型设计&#xff1b;其次&#xff0c;参照一体化设计理念&…

深兰科技获评2024年度人工智能出海先锋奖

5月25日&#xff0c;以“亚洲新势力&#xff1a;创新、融合与可持续发展”为主题的亚洲品牌经济峰会2024深圳会议在深圳益田威斯汀酒店举办。本次活动由中国亚洲经济发展协会指导&#xff0c;亚洲国际品牌研究院主办&#xff0c;旨在搭建品牌创新与经济发展交流平台&#xff0c…

nginx安装部署问题

记一次nginx启动报错问题处理 问题1 内网部署nginx&#xff0c;开始执行make&#xff0c;执行不了&#xff0c;后面装了依赖的环境 yum install gcc-c 和 yum install -y pcre pcre-devel 问题2&#xff0c;启动nginx报错 解决nginx: [emerg] unknown directive “stream“ in…

java版本数字化时代的智能ERP管理系统:引 领企业高 效管理与创新发展

随着数字化浪潮的席卷&#xff0c;现代企业对于高 效、稳定、易于扩展的管理系统需求愈发迫切。为了满足这一需求&#xff0c;我们倾力打造了一款基于Java技术的企业级资源规划&#xff08;ERP&#xff09;管理系统。该系统以Spring Cloud Alibaba、Spring Boot、MybatisPlus、…

[Linux打怪升级之路]-进程和线程

前言 作者&#xff1a;小蜗牛向前冲 名言&#xff1a;我可以接受失败&#xff0c;但我不能接受放弃 如果觉的博主的文章还不错的话&#xff0c;还请点赞&#xff0c;收藏&#xff0c;关注&#x1f440;支持博主。如果发现有问题的地方欢迎❀大家在评论区指正 目录 一、进程 1…

[UE5]安卓调用外置摄像头拍照(之显示画面)

目录 部分参考文献&#xff08;有些有用的我没标&#xff0c;没放上来&#xff09; 要点 总蓝图 结果 部分参考文献&#xff08;有些有用的我没标&#xff0c;没放上来&#xff09; 【UE】获取USB摄像头画面_虚幻捕获硬件摄像头-CSDN博客 UE4安卓调用摄像头拍照确保打…

C#中结构struct能否继承于一个类class,类class能否继承于一个struct

C#中结构struct能否继承于一个类class&#xff0c;类class能否继承于一个struct 答案是&#xff1a;都不能。 第一种情行&#xff0c;尝试结构继承类 报错&#xff1a;接口列表中的类型"XX"不是接口interface。 一般来说&#xff0c;都是结构只能实现接口&#x…

怎样快速查找网页代码中存在的错误?

计算机很机械&#xff0c;代码中存在微小的错误&#xff0c;计算机就得不到正确的运行结果。比如&#xff0c;一个字母的大小写、比如&#xff0c;个别地方丢掉了一个符号、、、如此等等。这就要求程序员和计算机是心灵相通的&#xff0c;不能有任何的“隔阂”。 但是&#xf…

LeetCode516:最长回文子序列

题目描述 给你一个字符串 s &#xff0c;找出其中最长的回文子序列&#xff0c;并返回该序列的长度。 子序列定义为&#xff1a;不改变剩余字符顺序的情况下&#xff0c;删除某些字符或者不删除任何字符形成的一个序列。 代码 /*dp[i][j]&#xff1a;[i,j]的回文子序列长度为d…