table of Contents
https://gitee.com/cxy-xupeng/spring-boot-test.git
1. Connect to the database and be able to access
2. Integrate basic JDBC and data sources
By default, SpringBoot adopts the unified processing method of integrating Spring Data, adding a large number of automatic configurations, and shielding many settings.
git address:
https://gitee.com/cxy-xupeng/spring-boot-test.git
1. Connect to the database and be able to access
Let's create a project first
Select spring web under web and JDBC and MySQL drivers under SQL
After creating the project, you will find that we have introduced the following drivers:
And we also use the previous database:
table of Contents:
We don’t use application.properties this time, we use application.yml:
spring:
datasource:
username: root
password: xp880000
url: jdbc:mysql://localhost:3306/xupeng?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
测试类Springboot05DataJdbcApplicationTests
@SpringBootTest
@RunWith(SpringRunner.class)
public class Springboot05DataJdbcApplicationTests {
@Autowired
public DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
Note: If you start to report an error as follows
警告: Runner org.junit.internal.runners.ErrorReportingRunner (used on class com.xupeng.Springboot05DataJdbcApplicationTests) does not support filtering and will therefore be run completely.
import org.junit.Test;
Remember to replace the guide package corresponding to your @Test with this
result:
We are writing a class:
HelloController :
@Controller
public class HelloController {
@Autowired
JdbcTemplate jdbcTemplate;
@ResponseBody
@RequestMapping("/query")
public Map<String,Object> map(){
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from account");
return list.get(0);
}
}
Database table account:
result:
2. Integrate basic JDBC and data sources
First look at the directory structure:
1. Introduce druid data source
pom.xml :
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
application.yml: add type to set the data source, and set some attributes of druid below
spring:
datasource:
username: root
password: xp880000
url: jdbc:mysql://localhost:3306/xupeng?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
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,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
DruidConfig: configure filter
package com.xupeng.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid监控
//1.配置一个管理后台的servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2.配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
Check the result: Let's first go to the management background servlet set by ourselves, the login name and password are set by ourselves above
Then we check the sql monitoring after making a query:
Three, integrate mybatis
First look at the directory:
User
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserMapper
public interface UserMapper {
List<User> getAllUser();
}
UserMapper.xml (The xml file is best placed under resources, don’t mess around)
<?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.xupeng.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.xupeng.domain.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>
<select id="getAllUser" resultMap="BaseResultMap">
select * from user
</select>
</mapper>
DruidConfig
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid监控
//1.配置一个管理后台的servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
//2.配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
UserService
public interface UserService {
List<User> getAllUser();
}
UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> getAllUser() {
return userMapper.getAllUser();
}
}
UserController
@Controller
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "getusers",method = RequestMethod.GET)
@ResponseBody
public List<User> getUsers(){
List<User> userList = userService.getAllUser();
return userList;
}
}
Springboot05MybatisApplication
@SpringBootApplication
@MapperScan(value = "com.xupeng.mapper")
public class Springboot05MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot05MybatisApplication.class, args);
}
}
result:
Fourth, integrate JPA
Let's build a project first:
Let's take a look at the directory first:
User:
package com.xupeng.entity;
import javax.persistence.*;
//使用JPA注解配置映射关系
@Entity
@Table(name = "user")//如果省略,默认表名就是user
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
private Integer id;
@Column(name = "username",length = 255)
private String username;
@Column //省略默认列名就是属性
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserRepository: Note here that the type behind JpaRepository<User,Integer> must be specified, otherwise an error will be reported. And the class can be directly referenced
package com.xupeng.repository;
import com.xupeng.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}
UserController
package com.xupeng.controller;
import com.xupeng.entity.User;
import com.xupeng.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("/user")
public List<User> getUser(){
List<User> userList = userRepository.findAll();
return userList;
}
}
result: