欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > SpringBoot 整合 Mybatis:注解版

SpringBoot 整合 Mybatis:注解版

2025/5/22 22:32:29 来源:https://blog.csdn.net/SOS_suyan/article/details/145420393  浏览:    关键词:SpringBoot 整合 Mybatis:注解版

第一章:注解版

  1. 导入配置:
    <groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version>
    </dependency>
  2. 步骤:
    1. 配置数据源见 Druid 配置
    2. 创建表
    3. 创建实体类:
      public class Txperson {public class TxPerson {private int pid;private String pname;private String addr;private int gender;private Date birth;}
      }
    4. 创建 Mapper 层:
      @Mapper
      public interface TxPersonMapper {@Select("select * from tx_person")public List<TxPerson> getPersons();@Select("select * from tx_person t where t.pid = #{id}")public TxPerson getPersonById(int id);@Options(useGeneratedKeys =true, keyProperty = "pid")@Insert("insert into tx_person(pid, pname, addr,gender, birth)" +" values(#{pid}, #{pname}, #{addr},#{gender}, #{birth})")public void insert(TxPerson person);@Delete("delete from tx_person where pid = #{id}")public void update(int id);}
    5. 编写配置类解决驼峰模式和数据库中下划线不能映射的问题
      @Configuration
      public class MybatisConfig {@Beanpublic ConfigurationCustomizer getCustomizer(){return new ConfigurationCustomizer() {@Overridepublic void customize(org.apache.ibatis.session.Configuration configuration) {configuration.setMapUnderscoreToCamelCase(true);}};}
      }
      
    6. 进行测试:

第二章:SpringBoot 整合 MyBatis 配置文件

  1. 创建 sqlMapConfig.xml 配置文件
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration></configuration>
  2. 映射文件 PersonMapper.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="cn.tx.mapper.TxPersonMapper"><select id="getPersons" resultType="TxPerson">select * from tx_person</select>
    </mapper>

  3. 在 application.yaml 中配置 mybatis 的信息
    mybatis:config-location: classpath:mybatis/sqlMapConfig.xmlmapper-locations: classpath:mybatis/mapper/*.xmltype-aliases-package: cn.tx.springboot.jdbc_demo1

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词