• MyBatis操作数据库(XML方式)


    MyBatis是一个持久层框架,和Spring没有任何关系,可以用来简化数据库的操作!

    创建工作:

    创建Spring Boot工程,并导入MyBatis的起步依赖,Mysql的依赖等

    配置数据

    1. #配置数据库的连接字符串
    2. spring:
    3. datasource:
    4. url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8
    5. username: root
    6. password: 自己设定的密码
    7. driver-class-name: com.mysql.cj.jdbc.Driver

    本文主要讲解使用XML方式来操作数据库!!

    然而操作数据库主要是用来增删改查四个方面,因此,本文着重于增删改查来讲解!!

    在操作数据库之前,我们需要创建一个数据库:

    1. -- 创建数据库
    2. DROP DATABASE IF EXISTS mybatis_test;
    3. CREATE DATABASE mybatis_test DEFAULT CHARACTER SET utf8mb4;
    4. -- 使⽤数据数据
    5. USE mybatis_test;
    6. -- 创建表[⽤⼾表]
    7. DROP TABLE IF EXISTS userinfo;
    8. CREATE TABLE `userinfo` (
    9. `id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
    10. `username` VARCHAR ( 127 ) NOT NULL,
    11. `password` VARCHAR ( 127 ) NOT NULL,
    12. `age` TINYINT ( 4 ) NOT NULL,
    13. `gender` TINYINT ( 4 ) DEFAULT '0' COMMENT '1-男 2-⼥ 0-默认',
    14. `phone` VARCHAR ( 15 ) DEFAULT NULL,
    15. `delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
    16. `create_time` DATETIME DEFAULT now(),
    17. `update_time` DATETIME DEFAULT now(),
    18. PRIMARY KEY ( `id` )
    19. ) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
    20. -- 添加⽤⼾信息
    21. INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
    22. VALUES ( 'admin', 'admin', 18, 1, '18612340001' );
    23. INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
    24. VALUES ( 'zhangsan', 'zhangsan', 18, 1, '18612340002' );
    25. INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
    26. VALUES ( 'lisi', 'lisi', 18, 1, '18612340003' );
    27. INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
    28. VALUES ( 'wangwu', 'wangwu', 18, 1, '18612340004' );

    那么,此时我们需要创建一个UserInfo类,使其各个参数名称与数据库参数名称相同(类似)

    1. @Data
    2. public class UserInfo {
    3. private Integer id;
    4. private String username;
    5. private String password;
    6. private Integer age;
    7. private Integer gender;
    8. private String phone;
    9. private Integer deleteFlag;
    10. private LocalDateTime createTime;
    11. private LocalDateTime updateTime;
    12. }

    值得注意的是:由于Java参数名称语法的原因,不能带有"_"(下划线),因此,Java中参数名称与数据库中参数名称出现了不一样的情况!

    另外还需要在application.xml中引入配置:(必须)

    1. mybatis:
    2. configuration:
    3. #配置mybatis xml的文件路径,在resources/mapper创建所有表的xml文件
    4. mapper-locations: classpath:mapper/**Mapper.xml

    新创建的UserInfoXMLMapper.xml文件中存储:

    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.example.mapper.UserInfoXMLMapper">
    5. mapper>

    有了上述的前提,我们便开始步入正题吧!

    增:

    1. @Mapper
    2. public interface UserInfoXMLMapper {
    3. Integer insert(UserInfo userInfo);
    4. }
    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.example.mapper.UserInfoXMLMapper">
    5. <insert id="insert">
    6. insert into userinfo(username,password,age,gender,phone)
    7. values(#{username},#{password},#{age},#{gender},#{phone})
    8. insert>
    9. mapper>

    Spring Boot测试代码为:

    1. @Slf4j
    2. @SpringBootTest
    3. class UserInfoXMLMapperTest {
    4. @Autowired
    5. private UserInfoXMLMapper userInfoXMLMapper;
    6. @Test
    7. void insert() {
    8. UserInfo userInfo=new UserInfo();
    9. userInfo.setUsername("张三");
    10. userInfo.setPassword("123456");
    11. userInfo.setAge(18);
    12. userInfo.setGender(1);
    13. userInfo.setPhone("13512345678");
    14. Integer result = userInfoXMLMapper.insert(userInfo);
    15. log.info("受影响的行数: {},插入的id为:{}" ,result,userInfo.getId());
    16. }
    17. }

     代码的运行结果为:

    查询数据库:

    新插入的数据已经查询到!

    那么,我们在专门插入一个id为11的数据(方便后续测试自增主键)

    接下来进行自增主键:

    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.example.mapper.UserInfoXMLMapper">
    5. <insert id="insert" useGeneratedKeys="true" keyProperty="id">
    6. insert into userinfo(username,password,age,gender,phone)
    7. values(#{username},#{password},#{age},#{gender},#{phone})
    8. insert>
    9. mapper>

    删:

    删除id为1 的数据

    1. @Mapper
    2. public interface UserInfoXMLMapper {
    3. Integer delete(Integer id);
    4. }
    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.example.mapper.UserInfoXMLMapper">
    5. <delete id="delete">
    6. delete from userinfo where id=#{id}
    7. delete>
    8. mapper>

    Spring Boot测试代码:

    1. @Slf4j
    2. @SpringBootTest
    3. class UserInfoXMLMapperTest {
    4. @Autowired
    5. private UserInfoXMLMapper userInfoXMLMapper;
    6. @Test
    7. void delete() {
    8. Integer result = userInfoXMLMapper.delete(1);
    9. log.info("受影响的行数: {}" ,result);
    10. }
    11. }

    程序的运行结果为:

    查看数据库:

    对比发现,程序可以正常删除!!

    改:

    将id为2的数据其age改为100

    1. @Mapper
    2. public interface UserInfoXMLMapper {
    3. Integer update(UserInfo userInfo);
    4. }
    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.example.mapper.UserInfoXMLMapper">
    5. <update id="update">
    6. update userinfo set age=#{age} where id=#{id}
    7. update>
    8. mapper>

    Spring Boot测试代码;

    1. @Slf4j
    2. @SpringBootTest
    3. class UserInfoXMLMapperTest {
    4. @Autowired
    5. private UserInfoXMLMapper userInfoXMLMapper;
    6. @Test
    7. void update() {
    8. UserInfo userInfo=new UserInfo();
    9. userInfo.setId(2);
    10. userInfo.setAge(100);
    11. //
    12. // userInfo.setUsername("李四");
    13. // userInfo.setPassword("123456");
    14. //
    15. userInfoXMLMapper.update(userInfo);
    16. //log.info("受影响的行数: {}" ,result);
    17. }
    18. }

    代码的运行结果为;

    查看数据库:

    确实做出了更改!!

    查:

    查的话,涉及到数据库参数名与Java属性名不一致的情况,所以操作不是很容易,但是,方法也不少!我们来看一下吧!

    查1:as起别名

    这种操作不方便,正式的项目中一般不这么使用!所以便不再讲解,感兴趣可参考小编文章:

    MyBatis操作数据库(注解方式)-CSDN博客,关于起别名的操作,该里面有着详细的讲解!

    查2:配置application.yml文件

    配置文件(必须)

    1. mybatis:
    2. configuration:
    3. map-underscore-to-camel-case: true #自动驼峰转换

    1. @Mapper
    2. public interface UserInfoXMLMapper {
    3. List selectAll();
    4. }
    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.example.mapper.UserInfoXMLMapper">
    5. <select id="selectAll" resultType="com.example.model.UserInfo" >
    6. select * from userinfo
    7. select>
    8. mapper>

    Spring Boot测试代码:

    1. @Slf4j
    2. @SpringBootTest
    3. class UserInfoXMLMapperTest {
    4. @Autowired
    5. private UserInfoXMLMapper userInfoXMLMapper;
    6. @Test
    7. void selectAll() {
    8. List<UserInfo> userInfoXMLMappers=userInfoXMLMapper.selectAll();
    9. log.info("userInfoXMLMappers:{}",userInfoXMLMappers);
    10. }
    11. }

    代码的运行结果为:

    正常输出!

    查3:reultMap映射器
    1. @Mapper
    2. public interface UserInfoXMLMapper {
    3. List selectAll2();
    4. }
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    4. <mapper namespace="com.example.mapper.UserInfoXMLMapper">
    5. <!-- UserInfoXMLMappe指的是:要实现哪个接口?要写接口的全限定类名!(包名+类名) -->
    6. <resultMap id="BaseMap" type="com.example.model.UserInfo">
    7. <id column="id" property="id"></id>
    8. <result column="delete_flag" property="deleteFlag"></result>
    9. <result column="create_time" property="createTime"></result>
    10. <result column="update_time" property="updateTime"></result>
    11. </resultMap>
    12. <select id="selectAll2" resultMap="BaseMap" >
    13. <!-- 只有select需要写 resultType 其他的不需要 -->
    14. select * from userinfo
    15. </select>
    16. </mapper>

    Spring Boot测试代码:

    1. @Slf4j
    2. @SpringBootTest
    3. class UserInfoXMLMapperTest {
    4. @Autowired
    5. private UserInfoXMLMapper userInfoXMLMapper;
    6. @Test
    7. void selectAll2() {
    8. List<UserInfo> userInfoXMLMappers=userInfoXMLMapper.selectAll2();
    9. log.info("userInfoXMLMappers:{}",userInfoXMLMappers);
    10. }
    11. }

    该段代码的运行结果为:

     本文主要是用XML的方式来带领大家了解MyBatis来操作数据库。

  • 相关阅读:
    BP神经网络的MATLAB实现(含源代码)
    tail -f 与 tailf 的区别
    Java证明尼科梅彻斯定理
    C语言编程经典100例——11至20例
    【Web基础入门】一文搞懂HTML + CSS + JavaScript 简单了解
    SringMVC中个常见的几个问题
    力扣第376题 摆动序列 c++ 贪心
    集合嵌套之Arraylist集合存储HashMap元素并遍历
    Python解析MDX词典数据并保存到Excel
    彻底透彻Docker常用网络模式及应用场景
  • 原文地址:https://blog.csdn.net/weixin_64308540/article/details/136453178