SpringBoot整合Mybatis的两种方式。

一、注解方式

1.配置mybatis-spring-boot-starter

mybatis-spring-boot-starter就是springboot+mybatis可以完全注解不用配置文件,也可以简单配置轻松上手。

     <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

2.配置数据源的属性在application.xml或者application.yml中。

eg:

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

由于上面用到了阿里巴巴的dirid数据源,不是springboot默认的数据源,所以需要对其进行配置。

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource(){
        return new DruidDataSource();
    }
}

3.创建表和实体类

eg:

public class Person {
    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 之后就可以对其进行的单元测试

6.解决驼峰模式和数据库中下划线不能映射的问题。

将下面代码对其进行配置就可以解决。

@Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer getCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

7.mapper过多,可以在对应的类上不指定@mapper,但是必须通过扫描器注解来扫

eg:@MapperScan(“对应的包”)

二、 配置文件整合

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>

  1. 需要配置映射文件的配置,eg: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">
//其中 namespace="cn.tx.mapper.TxPersonMapper"是其映射类的方法的包路径
<mapper namespace="cn.tx.mapper.TxPersonMapper">
    <select id="getPersons" resultType="TxPerson">
        select * from tx_person
    </select>
</mapper>

  1. 编写mapper对应的接口类
    无需任何的注解,springboot会自动的扫描appliction.xml配置路径的mapper文件,然后通过mapper文件中的中的namespace和id来定位到其类的方法。
@Mapper
public interface UserMapper {
    List<person> getAll();
}
  1. 在application.yaml中配置mybatis的信息
mybatis:
  config-location: classpath:mybatis/sqlMapConfig.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
    //别名
  type-aliases-package: cn.tx.springboot.jdbc_demo1

  1. 注入对应的mapper即可使用。
发布了29 篇原创文章 · 获赞 0 · 访问量 3819

猜你喜欢

转载自blog.csdn.net/Demon_HL/article/details/103966130