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 {
          @Bean
          public ConfigurationCustomizer getCustomizer(){
              return new ConfigurationCustomizer() {
                  @Override
                  public 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 configuration
         PUBLIC "-//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.xml
      mapper-locations: classpath:mybatis/mapper/*.xml
      type-aliases-package: cn.tx.springboot.jdbc_demo1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值