SpringBoot整合JDBC、SpringBoot整合Mybatis、SpringBoot中使用事务-day02中

6. SpringBoot的数据库访问

6.1 SpringBoot整合JDBC

第一步:pom中添加依赖

在这里插入图片描述

<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>

第二步:application.properties新增配置

在这里插入图片描述

#视图配置
#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

第三步:写个Service

在这里插入图片描述

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);
    }
}

第四步:写个Controller

在这里插入图片描述

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";
    }

}

第五步:App中配置

在这里插入图片描述

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);
    }
}

效果

在这里插入图片描述

  • 数据成功插入数据库
    在这里插入图片描述

6.2 SpringBoot整合Mybatis

第一步:pom中添加依赖

在这里插入图片描述

<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>

第二步:数据库配置

  • 同上
    在这里插入图片描述
#视图配置
#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

第三步:MybatisMapper的两种写法

第一种:注解写法【不推荐使用】

在这里插入图片描述

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);
}

第二种:xml写法【推荐使用】

在这里插入图片描述

  • 修改方便(项目上线后打成war或jar由于是.xml文件也能修改,而.java文件会在编译后变成.class文件打开后乱码修改困难)
    在这里插入图片描述
<?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>

使用xml写法的注意事项

  • 由于默认的.xml文件在打包时是不进入包中的,但是我们运行项目时是要使用.xml文件的,而包中没有,这样就会报错
  • 所以需要配置在打包时也将.xml文件打包进包中
    在这里插入图片描述
  • 在pom中添加(如要将.xml文件放入resources资源文件夹下统一管理,修改下面的目录为src/main/resources即可)
<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
  </resources>
</build>

第四步:修改UserService

在这里插入图片描述
在这里插入图片描述

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);
    }
}

第五步:在UserController中添加方法

在这里插入图片描述

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);
    }

}

第六步:App中添加Mybatis扫描

在这里插入图片描述

效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

6.3 SpringBoot中使用事务

  • Service实现类上(或是需要使用事务的地方)加个@Transactional注解即可
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43414199/article/details/109293508