Little sister's detailed SpringBoot tutorial: Getting started Connecting Mysql and Druid data sources and integrating MyBatis (3)

1. Integrate the use of JDBC

1. Create a project

Select the required dependencies: web and mysql drivers

2. Open the project

Configure database information in the project configuration file **(application.yml)**

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

Configure the time zone and character encoding in the url.

**driver-class-name:** is also different from the previous version, the previous one is com.mysql.cj.jdbc.Driver

3. Use our Idea to connect to our mysql database

1.

In test, test the database connection

 @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws Exception{
    
    
        /*查看获取的数据源*/
        System.out.println(dataSource.getClass());

        /*获取连接*/
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

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

5. Finally, test whether the data can be queried

Create a controller

The data source and configuration have been injected into JdbcTemplate, so we can inject JdbcTemplate.

Hit the point!

We don't have entity classes here, so how do we get our data?

We can use List<Map<String,Object>> to encapsulate our data

 @Autowired
    JdbcTemplate jdbcTemplate;
    @GetMapping("/hello")
    public List<Map<String,Object>> jdbcQuery(){
    
    
        String sql = "select * from customer";
        List<Map<String, Object>> list_map = jdbcTemplate.queryForList(sql);
        return list_map;
}

Finally visit http://localhost:8080/hello .

Hit the point!

We can check the source code of jdbcTemplate and take a look

6. Finally, simply add, delete, modify and check

 @Autowired
    JdbcTemplate jdbcTemplate;
    @GetMapping("/hello")
    public List<Map<String,Object>> getUser(){
    
    
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }

    @GetMapping("/addUser")
    public String addUser(){
    
    
        String sql = "insert into user(name,gender) values('鲁班大师','男')";
        jdbcTemplate.update(sql);
        return "update/ok";
    }

    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id){
    
    
        String sql = "update user set name=?,gender=? where id = "+id;
        Object[] objects = new Object[2];
        objects[0] = "木兰";
        objects[1] = "女";
        jdbcTemplate.update(sql,objects);
        return "update/ok";
    }

    @GetMapping("/delUser/{id}")
    public String delUser(@PathVariable("id") int id){
    
    
        String sql = "delete from user where id = "+id;
        jdbcTemplate.update(sql);
        return "del/ok";
    }

2. Integrate Druid data source

1. Import Druid dependencies

https://mvnrepository.com/artifact/com.alibaba/druid

2. To use the Druid data source, remember to change to Druid

Change in configuration

type: com.alibaba.druid.pool.DruidDataSource

3. Let's configure some parameters to test:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    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,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3. The power of Druid is that he can configure things

1. Create a config package, create DruidConfig.java below for configuration

After creation, first add @Configuration to the file

**Knock the point! **Because log4j is used here, we must import log4j's pom dependency

After writing, it must be injected into the Bean

<!--log4j-->
<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
</dependency>
@Configuration
public class DruidConfig {
    
    

    /*我们想要使用在配置文件中给Druid配置的属性,那么我们就要将这个方法和配置文件绑定到一起
    *        所以要将这个方法交给Bean管理,并且添加配置文件 @ConfigurationProperties
    * */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
    
    
        return new DruidDataSource();
    }

    /*后台监控 : web.xml  , ServletRegistrationBean*/
    /*因为 SpringBoot  内置了 Servlet容器  所以没有web.xml 替代方法:ServletRegistrationBean*/
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
    
    
        ServletRegistrationBean<Servlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        /*后台需要有人登录,账号密码配置*/
        Map<String, String> initParameters = new HashMap<>();

        /*增加配置*/
        /*配置账号密码,账号密码的key值是固定不变的 loginUsername  loginPassword*/
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123");

        /*允许访问*/
        initParameters.put("allow","");

        /*禁止访问  后边写IP地址*/
        initParameters.put("kuangshen","192.168.11.123");

        bean.setInitParameters(initParameters);
        return bean;
    }

    /*配置一个过滤器 filter*/
    @Bean
    public FilterRegistrationBean filterFilterRegistrationBean(){
    
    
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        /*这个是阿里巴巴的过滤器*/
        bean.setFilter(new WebStatFilter());
        /*可以过滤那些请求呢?*/
        Map<String, String> initParameters = new HashMap<>();

        /* 这些东西不进行统计 ~~    map的key值  是我们在WebStatFilter过滤器中查看源码得到的*/
        initParameters.put("exclusions","*.js,*.css,/druid/**");

        bean.setInitParameters(initParameters);
        return bean;
    }

}


4. Integrate MyBatis

1. Integration package

mybatis-spring-boot-start

This package is not official spring boot

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


2. Write database configuration and test

3. Import lombok dependencies and write pojo classes

 <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

Pojo.User type

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    
    
    private Integer id;
    private String name;
    private String gender;
}

4. Write the mapper interface

The mapper annotation indicates that this is a mapper class

You can also add the annotation @MapperScan("com.kuangshen.mapper") to the main class to scan all classes under the mapper

@Mapper/*这个注解表明了这是 mybatis 的mapper类*/
@Repository/*Dao层使用 @Repository 交给Spring */
public  interface UserMapper {
    
    

    /*查询所有用户*/
    List<User> getAllUser();

    /*查询单个用户*/
    User getUserById(int id);

    /*添加用户*/
    void addUser(User user);

    /*更改用户*/
    void updateUser(User user);

    /*删除用户*/
    void deleteUser(int id);
}

5. The mapper.xml file is placed in the resources directory

Create mybatic -> mapper -> UserMapper.xml in the resources directory

**xml configuration information can be found in the Chinese document of mybatis: **https://mybatis.org/mybatis-3/zh/getting-started.html

<?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="com.kuangshen.mapper.UserMapper">

</mapper>

First of all! ! First change the namespace to our own mapping file

To add and configure the location of our mapper file in the yml file! !

# 整合mybatis
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.kuangshen.mapper

Start to write our mapper.xml file based on our mapper interface

When inserting, the type user is passed in, just write name and id directly, user.id is not needed, otherwise it will not be found

<?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="com.kuangshen.mapper.UserMapper">
    <select id="getAllUser" resultType="com.kuangshen.pojo.User">
        select * from user
    </select>

    <select id="getUserById" resultType="com.kuangshen.pojo.User">
        select * from user where id = #{
    
    id}
    </select>

    <insert id="addUser" parameterType="com.kuangshen.pojo.User">
        insert into user(id,name,gender) values(#{
    
    id},#{
    
    name},#{
    
    gender})
    </insert>

    <update id="updateUser" parameterType="com.kuangshen.pojo.User">
        update user set name=#{
    
    user.name} , gender=#{
    
    user.gender} where id=#{
    
    user.id}
    </update>

    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{
    
    id}
    </delete>

</mapper>

6. Use the controller to complete the addition, deletion, and modification check

@RestController
public class UserController {
    
    

    @Autowired
    UserMapper userMapper;
    /*查询所有用户*/
    @GetMapping("/getAllUser")
    public List<User> getAllUser(){
    
    
        List<User> allUser = userMapper.getAllUser();
        return allUser;
    }
    /*根据用户ID查询用户*/
    @GetMapping("/getUserById/{id}")
    public String getUserById(@PathVariable("id") int id){
    
    
        userMapper.getUserById(id);
        return "delete OK";
    }
    /*添加用户*/
    @GetMapping("/addUser")
    public String addUser(){
    
    
        User user = new User();
        user.setName("王五");
        user.setGender("男");
        user.setId(5);
        userMapper.addUser(user);
        return "add OK!";
    }
    /*更新用户*/
    @GetMapping("/updateUser")
    public String updateUser(){
    
    
        return "update  ok !";
    }
    /*删除用户*/
    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
    
    
        userMapper.deleteUser(id);
        return "delete OK!";
    }
}


Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/113931024