SpringBoot(四)——数据源的自动配置

1 Springboot数据源自动配置

1.1 数据源自动管理

使用jdbc,需要的依赖和springboot的应用场景:

<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-jdbc</artifactId> 
</dependency> 
 
<dependency> 
   <groupId>mysql</groupId> 
   <artifactId>mysql-connector-java</artifactId> 
   <scope>runtime</scope> 
</dependency>

Spring默认使用Hikari数据源,我们也可以在application.yaml文件中自己配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testspring
    username: root
    password: 123456
    #type: com.zaxxer.hikari.HikariDataSource #默认的
    type: com.alibaba.druid.pool.DruidDataSource

1.2 数据源自动配置原理

在数据源自动配置类里面我们可以看到默认支持的数据源类型。
在这里插入图片描述
也可以看到三种数据源的配置。
在这里插入图片描述
点开starter-jdbc,可以看到Hikari是默认的数据源。
在这里插入图片描述

1.3 配置druid数据源

druid所需依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.9</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.15</version>

    <exclusions>
        <exclusion>
            <groupId>javax.jms</groupId>
            <artifactId>jms</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.jdmk</groupId>
            <artifactId>jmxtools</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.jmx</groupId>
            <artifactId>jmxri</artifactId>
        </exclusion>
    </exclusions>
</dependency>

给数据源配置属性:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testspring
    username: root
    password: 123456
    #type: com.zaxxer.hikari.HikariDataSource #默认的
    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

创建数据源注册类:

@Configuration
public class DatasourceConfig {

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

使用数据源:

@RestController
public class HelloController {

    @Autowired
    private DataSource dataSource;

    @RequestMapping("/hello")
    public String hello(){
        return "helloworld";
    }
}

现在数据源已经配置好了:
在这里插入图片描述

2 jdbcTemplate 自动配置

在数据库中建表:

SET FOREIGN_KEY_CHECKS=0; 
 
-- ---------------------------- 
-- Table structure for tx_user 
-- ---------------------------- 
DROP TABLE IF EXISTS `tx_user`; 
CREATE TABLE `tx_user` ( 
  `username` varchar(10) DEFAULT NULL, 
  `userId` int(10) NOT NULL, 
  `password` varchar(10) DEFAULT NULL, 
  PRIMARY KEY (`userId`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入数据:
在这里插入图片描述
配置及Controller:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testspringboot?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    # 其他数据源需要配置的东西
    # ...
@RestController
public class JdbcController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/query")
    public List<Map<String, Object>> query(){
        List<Map<String,Object>> maps = jdbcTemplate.queryForList("select * from tx_user");
        return maps;
    }
}

发送请求:
在这里插入图片描述

3 MyBatis自动配置

3.1 注解方式

所需依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.9</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.15</version>

    <exclusions>
        <exclusion>
            <groupId>javax.jms</groupId>
            <artifactId>jms</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.jdmk</groupId>
            <artifactId>jmxtools</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.jmx</groupId>
            <artifactId>jmxri</artifactId>
        </exclusion>
    </exclusions>
</dependency>

配置数据源相关属性(同上)

创建数据库表

create table preson(
pid int(20) not null auto_increment primary key,
pname varchar(50) default null,
addr varchar(50) default null,
gender int(2) default null,
birth date default null);

insert into preson values
(1,'wxy','shandong','1','1999-10-29'),
(2,'meteor','liaoning','2','2020-10-27');

创建javaBean:

public class Person {
    private int pid;
    private String pname;
    private String addr;
    private int gender;
    private Date birth;
    //getter and setter
}

创建Mapper:

@Mapper
public interface PersonMapper {

    @Select("select * from preson where pid = #{pid}")
    public Person selectById(int pid);

    @Select("select * from preson")
    public List<Person> selectAll();

    @Insert("insert into preson(pid,pname,addr,gender,birth)values(#{pid},#{pname},#{addr},#{gender},#{birth}")
    public void insert(Person p);

    @Delete("delete from preson where pid = #{pid}")
    public void delete(int pid);
}

Controller:

@RestController
public class HelloController {

    @Autowired
    private PersonMapper personMapper;

    @RequestMapping("selectById")
    public Person selectById() {
        return personMapper.selectById(1);
    }

    @RequestMapping("selectAll")
    public List<Person> selecAll(){
        return personMapper.selectAll();
    }
}

一些细节

  • mapper接口上的@Mapper可以用启动类上的@MapperScan("com.wxy.springmybatis.mapper")代替
  • 数据库和javaBean之间属性驼峰命名和下划线命名默认是不能相互转换的,可通过下面的方法设置转换为真:
/**
 * 设置数据库和javaBean的下划线命名和驼峰命名转换,不常用
 */
@Configuration
public class MybatisConfig {
    @Bean
    public ConfigurationCustomizer customizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

3.2 配置文件方式

在SpringBoot中mybatis的核心配置xml是不需要创建的,因为完全可以通过配置文件进行配置,而mapper映射还是需要配置的:

<?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">
<!-- resource/mapper/PersonMapper.xml -->
<mapper namespace="com.wxy.springmybatis.mapper.PersonMapper">
    <select id="selectById" resultType="Person" parameterType="int">
        select * from preson where pid = #{pid}
    </select>
    <select id="selectAll" resultType="Person">
        select * from preson
    </select>
    <insert id="insert" parameterType="Person">
        <selectKey keyProperty="pid" resultType="int" order="BEFORE">
            select last_insert_id()
        </selectKey>
        insert into preson(pid,pname,addr,gender,birth)values(#{pid},#{pname},#{addr},#{gender},#{birth}
    </insert>
    <delete id="delete" parameterType="int">
        delete from preson where pid = #{pid}
    </delete>
</mapper>

配置文件的配置:

# mybatis的配置
mybatis:
  #config-location: classpath:sqlMapConfig.xml #核心配置文件位置,其实完全不需要,而且和下面的configuration冲突
  mapper-locations: classpath:mapper/*.xml #mapper映射文件
  configuration:
    map-underscore-to-camel-case: true #下划线和驼峰模式转换
  type-aliases-package: com.wxy.springmybatis.model #设置别名--类名,大小写不区分
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值