índice
- 6. Acesso ao banco de dados SpringBoot
-
- 6.1 SpringBoot integra JDBC
- 6.2 SpringBoot integra Mybatis
- 6.3 Usando transações no SpringBoot
6. Acesso ao banco de dados SpringBoot
6.1 SpringBoot integra JDBC
A primeira etapa: adicionar dependência em 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>
Etapa 2: Nova configuração em 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
A terceira etapa: escrever um serviço
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);
}
}
Etapa 4: escrever um controlador
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";
}
}
Etapa 5: configuração no aplicativo
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);
}
}
efeito
- Os dados foram inseridos com sucesso no banco de dados
6.2 SpringBoot integra Mybatis
A primeira etapa: adicionar dependência em 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>
Etapa 2: configuração do banco de dados
- O mesmo que acima
#视图配置
#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
Etapa 3: Duas maneiras de escrever MybatisMapper
O primeiro tipo: método de escrita de anotação [não recomendado]
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);
}
A segunda: escrita xml [uso recomendado]
- Fácil de modificar (depois que o projeto estiver online, ele pode ser modificado como war ou jar porque é um arquivo .xml, enquanto o arquivo .java se tornará um arquivo .class após a compilação e é difícil modificar o código truncado após a abertura)
<?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>
Precauções para usar a escrita xml
- Como o arquivo .xml padrão não entra no pacote durante o empacotamento, mas precisamos usar o arquivo .xml quando executamos o projeto, e não há pacote, ele relatará um erro
- Portanto, ele precisa ser configurado para também embalar o arquivo .xml no pacote ao empacotar
- Adicione o pom (se você quiser colocar o arquivo .xml na pasta de recursos para gerenciamento unificado, modifique o seguinte diretório para src / main / resources)
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
Etapa 4: Modificar 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);
}
}
Etapa 5: adicionar um método no 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);
}
}
Etapa 6: Adicionar Mybatis scan no aplicativo
efeito
6.3 Usando transações no SpringBoot
- Adicione uma anotação @Transactional à classe de implementação de serviço (ou onde você precisa usar transações)