整合JDBC+druid+MyBatis
1)jdbc
Sping Data 官网:https://spring.io/projects/spring-data
数据库相关的启动器 :可以参考官方文档:
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

application.yml:
spring:
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatistest?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
配置完这些东西后,我们就可以直接去使用了,因为SpringBoot已经默认帮我们进行了自动配置
测试:
@RestController
public class HelloController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @RequestMapping("/select")
    public  List<Map<String, Object>> select(){
        String sql="select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
}
JDBCTemplate
- 
即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate 
- 
数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。 
- 
Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用 
- 
JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的 JdbcTemplateConfiguration 类 
JDBCTemplate主要提供以下几类方法:
- 
execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句; 
- 
update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句; 
- 
query方法及queryForXXX方法:用于执行查询相关语句; 
- 
call方法:用于执行存储过程、函数相关语句。 
2)druid

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>

DruidConfig:
@Configuration
public class DruidConfig {
    //将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }
    //后台监控,相当于web.xml
    //因为springboot内置了servlet,没有web.xml,因此用ServletRegistrationBean来替代
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean srb = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //后台登录的账号密码
        HashMap<String, String> initParameters = new HashMap<>();
        //增加配置
        initParameters.put("LoginUsername","admin");//这里的key是固定的
        initParameters.put("LoginPassword","123456");
        //允许谁可以访问
        //initParameters.put("allow","");//默认允许所有都可以访问
        
        srb.setInitParameters(initParameters);//设置初始化参数
        return srb;
    }
    //过滤器
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean frb = new FilterRegistrationBean();
        frb.setFilter(new WebStatFilter());
        //可以过滤的请求
        HashMap<Object, Object> initParameters = new HashMap<>();
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        frb.setInitParameters(initParameters);
        return frb;
    }
}
applcation.yml:
spring:
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatistest?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
    type: com.alibaba.druid.pool.DruidDataSource
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    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:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
参考链接:https://mp.weixin.qq.com/s/wVAGOP1JdXZi5DMEsX1Aug
3)mybatis
1.mybatis整合包:
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
2.配置数据库连接信息(同上不变)
3.编写代码

注意:这里为了测试,可以先不写service层,实际业务中需要写service层
UserMapper.xml:
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kakafa.springbootjdbc.mapper.UserMapper">
    <select id="getUserList" resultType="user">
        select * from mybatistest.user;
    </select>
    <select id="getUserById" parameterType="int" resultType="user">
        select * from mybatistest.user where id = #{id};
    </select>
    <insert id="addUser" parameterType="user" >
        insert into mybatistest.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="user">
        update mybatistest.user
        set name=#{name},pwd=#{pwd}
        where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int">
        delete
        from mybatistest.user
        where id=#{id};
    </delete>
</mapper>
UserMapper:
@Mapper //是mybatis中的注解,表示将UserMapper交给Spring
@Repository //是springboot中的注解,表示这是一个dao层的类
//这个@Repository加不加都可以,因为@Mapper已经交给Spring容器管理了
public interface UserMapper {
    //获取全部用户
    List<User> getUserList();
    //根据id查询用户
    User getUserById(int id);
    //插入一个用户
    int addUser(User user);
    //修改用户
    int updateUser(User user);
    //删除用户
    int deleteUser(int id);
}
UserController:
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/queryUserList")
    public  List<User> queryUserList(){
        List<User> userList = userMapper.getUserList();
        return userList;
    }
}
yml中要配置mybatis:

4.pom.xml中解决静态资源导出问题
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

4)一些JDBC和数据源的解释



参考链接:https://www.cnblogs.com/goloving/p/14884802.html
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号