Springboot has its own datasource import dependency and mysql’s dependency

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>  <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> 12345678Copy the code

Tests that can now test connections in the test class

package com.jj.demo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @SpringBootTest class DemoApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { System.out.println("dataSource.getClass() = " + dataSource.getClass()); Conn = datasource.getConnection (); System.out.println("dataSource.getConnection() = " + conn); conn.close(); }} 1234567891011121314151617181920212223242526Copy the code

The test results show that the default is the Springboot connection YML configuration

# data source configuration spring: a datasource: type: com. Alibaba. Druid. Pool. DruidDataSource driver - class - name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/op? useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: Root password: 123456 druid: # initialSize: 5 # Minimum number of connections minIdle: 10 # Maximum number of connections maxActive: 20 # configuration for connecting waiting timeout time maxWait: how long is the interval to a 60000 # configuration testing, testing needs to be closed free connection, unit is a millisecond timeBetweenEvictionRunsMillis: 60000 # configure a connection in the pool minimum survival time, unit is a millisecond minEvictableIdleTimeMillis: 300000 # configure a connection in the pool the largest survival time, the unit is a millisecond maxEvictableIdleTimeMillis: ValidationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false webStatFilter: enabled: true statViewServlet: enabled: true 12345678910111213141516171819202122232425262728293031323334Copy the code

Control layer CRUD operations

package com.jj.demo.Controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Map; @RestController public class JdbcController { @Autowired JdbcTemplate jdbcTemplate; @requestMapping ("/viplist") public List<Map<String,Object>> show(){String SQL ="select * from VIP "; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); System.out.println("list = " + list); return list; } @requestMapping ("/add") public String add(){String SQL ="insert into VIP (name, PWD) values(' 123456','123456')"; int update = jdbcTemplate.update(sql); System.out.println("update = " + update); return "ok"; } @requestMapping ("/del") public String del(){String SQL ="delete from VIP where name=' '"; int update = jdbcTemplate.update(sql); System.out.println("sql = " + update); return "ok"; } @requestMapping ("/update") public String update(){String SQL ="update VIP set name=' 123' where PWD ='123'"; int update = jdbcTemplate.update(sql); System.out.println("update = " + update); return "ok"; }} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748Copy the code

Alibaba connection pool, yML add type attribute on the line. Import dependence

<! --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> 123456Copy the code

Run the test class and you can see that the current connection is alibaba

The 2020-12-22 15:55:32. 11524-333 the INFO [main] O.S.S.C oncurrent. ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor' 2020-12-22 15:55:32.813 INFO 11524 -- [main] com.jj.demo.DemoApplicationTests : Started DemoApplicationTests in 4.924 seconds (JVM running for 6.178) dataSource. GetClass () = class com.alibaba.druid.pool.DruidDataSource dataSource.getConnection() = Com. Alibaba. Druid. Proxy. JDBC. ConnectionProxyImpl @ 447 fa959 15:55:32 2020-12-22. 11524-933 the INFO [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor' 920-12-22 15:55:32.933 INFO 11524 - [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default' INFO [SpringContextShutdownHook] - {dataSource-1} closed  123456789Copy the code

Other CRUD operations are the same

Use Druid to do background monitoring

Create a new config class

package com.jj.demo.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.HashMap; @configuration public class Druidconfig {// Connect to our yML @configurationProperties (prefix = "spring.datasource") @bean public DataSource druidDataSource(){ return new DruidDataSource(); Public ServletRegistrationBean ServletRegistrationBean (){ServletRegistrationBean<StatViewServlet> Bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*"); // Set password HashMap<String, String> map = new HashMap<>(); Map. put("loginUsername","admin"); map.put("loginPassword","123456"); // Set who is allowed to access map.put("allow",""); // Set the initialization parameter bean.setinitParameters (map); return bean; } // Filter @bean public FilterRegistrationBean webdilter(){FilterRegistrationBean Bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); // Can filter those requests HashMap<String, String> stringStringHashMap = new HashMap<>(); Buguolv stringStringhashmap. put("exclusions","*.js,*.css,/druid/*"); // Initialize bean.setinitParameters (stringStringHashMap); return bean; }} 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758Copy the code

The effect





You can see some background monitoring!!

** Integrate mybatis **

Import dependence

<! <dependency> <groupId>org.mybatis.spring. Boot </groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.0.1 < / version > < / dependency > 123456Copy the code

Configure yML for Mybatis

Mybatis: configuration: mybatis: configuration: mybatis: configuration: Org. Apache. Ibatis. Logging. Stdout. StdOutImpl package # # integration an alias database if there are similar Such as user_name, named will _ after the letters of the capital, # map-underscore-to-camel-case: true # underscore-to-camel-case: true com.jj.demo.pojo mapper-locations: classpath:mybatis/mapper/*.xml 1234567891011Copy the code

Entity class I’m just a plain ID,name, PWD

interface



Simple CRUD, interface, and XML

package com.jj.demo.mapper; import com.jj.demo.pojo.vip; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; @mapper@repository public interface Vipdao {// check List< VIP > show(); // delete int del(int id); Int update(VIP VIP); // add int insertvip(VIP VIP); <} 123456789101112131415161718192021? The 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.jj.demo.mapper.Vipdao"> <! <select id="show" resultType=" VIP "> select * from VIP ParameterType ="int"> Delete from VIP where id=#{id} </delete> <! ParameterType =" parameterType "> update VIP set name=#{name} where id=#{id} </update> <! ParameterType =" parameterType "> insert into VIP (name, PWD) values (#{name},#{PWD}) </insert> </mapper> 123456789101112131415161718192021222324Copy the code

Control layer

package com.jj.demo.Controller; import com.jj.demo.mapper.Vipdao; import com.jj.demo.pojo.vip; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @restController Public class mybatisController {// Inject the dao layer that does not want to write the business layer directly. @requestMapping ("/show") public List< VIP > show(){List< VIP > show = vipdao.show(); return show; } @requestMapping ("/del1") public String del1(){int I = vipdao.del(36); return "ok"; } @requestMapping ("/up") public String up(){VIP VIP = new VIP (); Vip.setname (" feng Jiaojiao "); vip.setId(38); vipdao.update(vip); return "okk!" ; } @requestMapping ("/ins") public String in(){VIP VIP = new VIP (); Vip.setname (" feng Jiaojiao 1"); vip.setPwd("11111"); vipdao.insertvip(vip); return "vip1"; }} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748Copy the code

end!!!

Conclusion:

Thank you for reading this article, but also for you to prepare advanced Java architecture information, need friends can follow the wechat public number [Java programmers gathering] to obtain architecture information.