SpringBoot integrates JDBC, SpringBoot integrates Mybatis, SpringBoot uses transactions-day02

6. SpringBoot database access

6.1 SpringBoot integrates JDBC

The first step: add dependency in pom

Insert picture description here

<parent>
    <!--SpringBoot的父依赖-->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
  </parent>

  <dependencies>
    <!--SpringBoot配置web依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--引入freeMarker的依赖包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <!--JDBC-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--数据库驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--单元测试-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

Step 2: New configuration in application.properties

Insert picture description here

#视图配置
#spring.mvc.view.prefix=/WEB-INF/view/
#spring.mvc.view.suffix=.jsp

#server.port=8888
#server.context-path=/test

#数据库配置
spring.datasource.url=jdbc:mysql:///test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Step 3: Write a Service

Insert picture description here

package com.it.service.impl;

import com.it.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * @ClassName UserServiceImpl
 * @Author shuyy
 * @Date 2020/10/26
 **/
@Service
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private JdbcTemplate jdbcTemplate;//本来这里需要配置数据源,现在在SpringBoot中配置好了无需配置
    @Override
    public void register(String username, String password) {
    
    
        String sql = "insert into user(username,password) values(?,?)";
        jdbcTemplate.update(sql,username,password);
    }
}

Step 4: Write a Controller

Insert picture description here

package com.it.web.controller;

import com.it.model.User;
import com.it.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName HelloController
 * @Author shuyy
 * @Date 2020/10/25
 **/
@RestController//相当于声明Controller,并提供restful风格
//@EnableAutoConfiguration//自动配置不需要写Spring配置文件
@RequestMapping("user")
public class UserController {
    
    

    @Autowired
    private UserService userService;

    @RequestMapping("register")
    @ResponseBody
    public String register(String username,String password){
    
    
        userService.register(username,password);
        return "success";
    }

}

Step 5: Configuration in App

Insert picture description here

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

/**
 * @ClassName App
 * @Author shuyy
 * @Date 2020/10/25
 **/
@EnableAutoConfiguration//只能写一个,这里配置了,其它Controller无需写了
@ComponentScan(basePackages = {
    
    "com.it.web.controller","com.it.service"})//配置扫描包
//@ComponentScan(basePackages = {"com.it.web.controller",""})//配置多个扫描包
public class App {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(App.class,args);
    }
}

effect

Insert picture description here

  • Data is successfully inserted into the database
    Insert picture description here

6.2 SpringBoot integrates Mybatis

The first step: add dependency in pom

Insert picture description here

<parent>
    <!--SpringBoot的父依赖-->
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
  </parent>

  <dependencies>
    <!--SpringBoot配置web依赖-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--引入freeMarker的依赖包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <!--JDBC-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--数据库驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!--单元测试-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--Mybatis-->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.1.1</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

Step 2: Database configuration

  • Same as above
    Insert picture description here
#视图配置
#spring.mvc.view.prefix=/WEB-INF/view/
#spring.mvc.view.suffix=.jsp

#端口号配置
#server.port=8888
#项目名配置
#server.context-path=/test

#数据库配置
spring.datasource.url=jdbc:mysql:///test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Step 3: Two ways of writing MybatisMapper

The first type: annotation writing method [not recommended]

Insert picture description here

package com.it.mapper;


import com.it.model.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {
    
    

    @Insert("insert into user(username,password) values(#{username},#{password})")
    void save(@Param("username") String username,@Param("password") String password);

    @Select("select * from user where id = #{id}")
    User findUserById(@Param("id") Integer id);
}

The second: xml writing [recommended use]

Insert picture description here

  • Easy to modify (after the project is online, it can be modified as a war or jar because it is a .xml file, while the .java file will become a .class file after compilation and it is difficult to modify the garbled code after opening)
    Insert picture description here
<?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.it.mapper.UserMapper" >

    <insert id="save">
        insert into user (username,password) VALUES(#{0},#{1})
    </insert>
    <select id="findUserById" resultType="com.it.model.User" parameterType="int">
        select * from user where id = #{id}
    </select>
</mapper>

Precautions for using xml writing

  • Since the default .xml file does not enter the package when packaging, but we need to use the .xml file when we run the project, and there is no package, it will report an error
  • So it needs to be configured to also pack the .xml file into the package when packaging
    Insert picture description here
  • Add in the pom (if you want to put the .xml file in the resources folder for unified management, modify the following directory to src/main/resources)
<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
  </resources>
</build>

Step 4: Modify UserService

Insert picture description here
Insert picture description here

package com.it.service.impl;

import com.it.mapper.UserMapper;
import com.it.model.User;
import com.it.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName UserServiceImpl
 * @Author shuyy
 * @Date 2020/10/26
 **/
@Service
public class UserServiceImpl implements UserService {
    
    

    @Autowired
    private UserMapper userMapper;//这里如果报错,正常不影响运行,是springBean扫描所致,它是在运行时自动创建
    /*private JdbcTemplate jdbcTemplate;*/
    //本来这里需要配置数据源,现在在SpringBoot中配置好了无需配置
    @Override
    public void register(String username, String password) {
    
    
        /*String sql = "insert into user(username,password) values(?,?)";*/
        /*jdbcTemplate.update(sql,username,password);*/
        userMapper.save(username,password);
    }

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

Step 5: Add a method in UserController

Insert picture description here

package com.it.web.controller;

import com.it.model.User;
import com.it.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName HelloController
 * @Author shuyy
 * @Date 2020/10/25
 **/
@RestController//相当于声明Controller,并提供restful风格
//@EnableAutoConfiguration//自动配置不需要写Spring配置文件
@RequestMapping("user")
public class UserController {
    
    

    @Autowired
    private UserService userService;

    @RequestMapping("register")
    @ResponseBody
    public String register(String username,String password){
    
    
        userService.register(username,password);
        return "success";
    }

    @RequestMapping("find")
    @ResponseBody
    public User find(Integer id){
    
    
        return userService.findUserById(id);
    }

}

Step 6: Add Mybatis scan in App

Insert picture description here

effect

Insert picture description here
Insert picture description here
Insert picture description here

6.3 Using transactions in SpringBoot

  • Add a @Transactional annotation to the Service implementation class (or where you need to use transactions)
    Insert picture description here
    Insert picture description here
    Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43414199/article/details/109293508