6、SpringBoot:整合JDBC,Druid,Mybatis

1、SpringBoot整合JDBC

1.1、新建一个springboot项目

在这里插入图片描述

1.2、在application.yml中写配置

spring:
  datasource:
    username: root
    password: root
    # 新版本里边需要配置时区
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=false&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

1.3、在Test里边进行测试

@SpringBootTest
class SpringbootDataApplicationTests {

    // 注入数据源
    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        // 查看默认的数据源
        System.out.println(dataSource.getClass());

        // 获得数据库连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        // 关闭连接
        connection.close();
    }
}

1.5、结果

在这里插入图片描述

1.4、编写controller

注意使用@RestController注解,需要导入web启动依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
@RestController
public class JDBCController {

    @Autowired
    JdbcTemplate jdbcTemplate;// springboot配置好的模板

    // 查询数据库的所有信息
    // 如果没有实体类,可以使用map去获取数据库中的数据
    @GetMapping("/user")
    public List<Map<String,Object>> userList(){
        String sql = "select * from user";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }

    // 添加数据
    @GetMapping("/add")
    public String addList(){
        String sql = "insert into user(id,name,pwd) values(7,'小王','1111')";
        jdbcTemplate.update(sql);
        return "插入成功";
    }
    // 修改数据
    @GetMapping("/update/{id}")
    public String updateList(@PathVariable("id") Integer id){
        String sql = "update user set name=?,pwd=?   where id="+id ;

        // 封装
        Object[] objects = new Object[2];
        objects[0] = "张三";
        objects[1] = "123";
        jdbcTemplate.update(sql,objects);
        return "修改成功";
    }
    // 删除数据
    @GetMapping("/delete/{id}")
    public String deleteList(@PathVariable("id") Integer id){
        String sql = "delete from user where id = ?";
        jdbcTemplate.update(sql,id);
        return "删除成功";
    }
}

2、SpringBoot整合Druid

2.1、导入依赖

		<!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.1</version>
        </dependency>

2.2、启动test测试类

连接数据库的底层不会改变,都是JDBC,

改变数据源只需要在application.yml配置中做修改

	type: com.alibaba.druid.pool.DruidDataSource
spring:
  datasource:
    username: root
    password: root
    # 新版本里边需要配置时区
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=false&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

在这里插入图片描述
查看数据源:

在这里插入图片描述

2.3、在application.yml中添加配置

	#SpringBoot默认是不注入这些的,需要自己绑定
    #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.Properity
    #则导入log4j 依赖就行
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

加入log4j依赖

		<!-- log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

2.4、启动测试,查看结果

在这里插入图片描述

查询结果和JDBC没有区别,区别在于Druid可以自定义配置

2.5、自定义配置

新建config目录,在config目录下新建DruidConfig

一定要加@Configuration注解,否则无法生效

1、首先将yml中的配置绑定到DruidConfig中

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

2、配置后台监控

因为SpringBoot内置了servlet容器,所以没有web.xml

注意:一定要将配置注册到Bean中

    /**
     * 后台监控   相当于web.xml
     * 因为SpringBoot内置了servlet容器,所以没有web.xml
     */

    @Bean
    public ServletRegistrationBean StatViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        // 后台需要有人登陆,账号密码配置
        // 根据源代码进行编写
        HashMap<String, String> initParameters = new HashMap<>();
        // 增加配置
        // loginUsername,loginPassword  参数是固定的
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123");

        // 允许谁可以访问,也可以禁止谁访问
        // 这里表示谁都可以访问
        initParameters.put("allow","");

        // 设置初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }

3、启动测试

在这里插入图片描述
输入用户名,密码后效果:

在这里插入图片描述

4、执行sql语句

可以在Driud里边查看到sql

在这里插入图片描述

5、也可以自定义过滤器

    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        // 设置一个过滤器
        bean.setFilter(new WebStatFilter());

        // 设置过滤请求
        HashMap<String, String> initParameters = new HashMap<>();
        // 这些路径不进行过滤
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        return bean;
    }

3、SpringBoot整合Mybatis

项目结构

在这里插入图片描述

新建一个springboot项目,勾选web,sql驱动,和sql API模块

3.1、导入整合依赖

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

3.2、编写连接数据库的配置

spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=false&serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3.3、在Test测试类中进行测试

@SpringBootTest
class SpringbootMybatisApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }

}

结果:

在这里插入图片描述

连接成功

3.4、创建pojo实体类

public class User implements Serializable {
    private Integer id;
    private String name;
    private String pwd;
}

3.5、创建一个mapper接口,编写增删改查方法

@Mapper // 表示这是一个mybatis的mapper类
@Repository
public interface UserMapper {
    // 查询所有的用户
    List<User> selectAllUser();
    // 通过id查询用户
    User selectUserById(Integer id);
    // 增加用户
    int addUser(User user);
    // 修改用户
    int updateUser(User user);
    // 删除用户
    int deleteUser(Integer id);
}

3.6、在resource下新建一个mappers目录,新建UserMapper.xml配置文件

  1. 第一种方式:

在编写xml配置文件前需要在application.properties中进行配置(起别名和扫描位置)

	# 整合mybatis
	# 起别名
	mybatis.type-aliases-package=com.jl.pojo
	# xml文件的位置
	mybatis.mapper-locations=classpath:mappers/*.xml
  1. 第二种方式
	@MapperScan("com.jl.mapper")

xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jl.mapper.UserMapper">
    <!-- 查询所有的用户   -->
    <select id="selectAllUser" resultType="user">
        select * from user;
    </select>
    <!-- 通过id查询用户  -->
    <select id="selectUserById" resultType="user">
        select * from user where id = #{id};
    </select>
    <!-- 增加用户   -->
    <insert id="addUser" parameterType="user">
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
    <!-- 修改用户   -->
    <update id="updateUser" parameterType="user">
        update user set name=#{name},pwd=#{pwd}  where id=#{id};
    </update>
    <!-- 删除用户   -->
    <delete id="deleteUser">
        delete from user where id=#{id}
    </delete>
</mapper>

3.7、编写server层业务

  1. UserService
public interface UserService {
    // 查询所有的用户
    List<User> selectAllUser();
    // 通过id查询用户
    User selectUserById(Integer id);
    // 增加用户
    int addUser(User user);
    // 修改用户
    int updateUser(User user);
    // 删除用户
    int deleteUser(Integer id);
}
  1. UserServiceImpl
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> selectAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public User selectUserById(Integer id) {
        return userMapper.selectUserById(id);
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int deleteUser(Integer id) {
        return userMapper.deleteUser(id);
    }
}

3.8、编写controller层业务

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/all")
    public List<User> selectAllUser(){
        List<User> userList = userService.selectAllUser();
        for (User user : userList) {
            System.out.println(user);
        }
        return userList;
    }

    @GetMapping("/id/{id}")
    public User selectUserById(@PathVariable("id") Integer id){
        User user = userService.selectUserById(id);
        System.out.println(user);
        return user;
    }

    @GetMapping("/add")
    public String addUser(User user){
        userService.addUser(new User(7,"jj","123"));
        return "插入成功";
    }

    @GetMapping("/update")
    public String updateUser(User user){
        userService.updateUser(new User(7,"hh","111"));
        return "修改成功";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") Integer id){
        userService.deleteUser(7);
        return "删除成功";
    }
}

学习视频:https://www.bilibili.com/video/BV1PE411i7CV?p=32

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值