Foreword:
The general process of Spring boot integrating mybatis is as follows:
(1) Create a new maven project and introduce relevant dependencies in the pom.xml file.
(2) Configuration file application.yml (application.properties)
(3) Write pojo entity class
(4) Write Mapper interface
(5) Write Service class
(6) Write Controller class
(7) Write the main class for startup
With JdbcTemplate, you don't need to write the Service class, but you need to write a bean instance that configures the JdbcTemplate in the Configuration class.
1. Project directory structure
2. New MVN project
The creation process needs to fill in groupId and artifactId, which are all springboottest.
3. pom.xml fills in all the dependent libraries. The content is as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboottest</groupId>
<artifactId>springboottest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-mybatis</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Fourth, create the database table user and configuration:
See Spring Mybatis instance SqlSessionDaoSupport mixed with xml configuration and annotations . In order to demonstrate multiple data sources, create user tables in yiibai and test2 respectively, and the content of the inserted data is different (just write it, as long as the two are not the same).
-- Database: `yiibai`
INSERT INTO `user` (`id`, `name`, `dept`, `website`, `phone`, `birthday`) VALUES
(1, 'yiibai1', 'Tech', 'http://www.yiibai.com', '13800009911', '1973-11-05'),
(2, '依依2', 'Tech', 'http://www.zjptcc.com', '13800009922', '1973-11-05'),
(3, 'yiibai3', 'Tech', 'http://www.zjptcc.com', '13800009900', '1973-11-05'),
(4, 'yiibai4', 'Tech', 'http://www.zjuni.com', '13800009900', '1973-11-05');
--
-- Database: `test2`
--
INSERT INTO `user` (`id`, `name`, `dept`, `website`, `phone`, `birthday`) VALUES
(1, 'yiibai1', 'Tech', 'http://www.yiibai.com', '13800009911', '1973-11-05'),
(2, '依蓓2', 'Tech', 'http://www.zjptcc.com', '13800009900', '1973-11-05'),
(3, '依蓓3', 'Tech', 'http://www.zjptcc.com', '13800009900', '1973-11-05'),
(4, '依依4', 'Tech', 'http://www.zjuni.com', '13800009900', '1973-11-05');
The configuration of the data source is in the application.yml of the MVN project
spring:
datasource:
url : jdbc:mysql://localhost:3306/yiibai?useSSL=false
username : your-user
password : your-passwd
driver-class-name : com.mysql.jdbc.Driver
test2ds:
url : jdbc:mysql://localhost:3306/test2?useSSL=false
username : your-user
password : your-passwd
driver-class-name : com.mysql.jdbc.Driver
Modify username and password to suit your database environment
Five, DAO layer interface and entity class
Similar to the example in the Spring Mybatis instance SqlSessionDaoSupport mixed with xml configuration and annotations . Among them, add @Mapper
annotation to IUser and remove the public User oneByID(int id); method. The modified content is as follows:
package com.yiibai.mybatis.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.yiibai.mybatis.models.User;
@Mapper
public interface IUser {
@Select("select * from user where id= #{id}")
public User getUserByID(int id);
@Insert("insert into user(id,name, dept,phone,website,birthday) values(#{id},#{name}, #{dept},#{phone}, #{website}, #{birthday})")
public int insertUser(User user);
@Delete("delete from user where id=#{id}")
public int deleteUserById(int id);
@Update("update user set name=#{name},dept=#{dept},phone=#{phone},website=#{website},birthday=#{birthday} where id=#{id}")
public int updateUser(User user);
@Select("select * from user")
public List<User> getAllUser();
}
The content of the User class remains unchanged. Add a UserRowMapper class and use it in the JdbcTemplate function. For details, see the third point 2 in Spring's persistent instance . The content is as follows:
package com.yiibai.mybatis.models;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class UserRowMapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int arg1) throws SQLException {
// TODO 自动生成的方法存根
return new User(rs.getInt("id"),rs.getString("name"),rs.getString("dept")
,rs.getString("phone"),rs.getString("website"),rs.getDate("birthday"));
}
}
6. Server class
package com.yiibai.mybatis.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yiibai.mybatis.dao.IUser;
import com.yiibai.mybatis.models.User;
@Service(value="userService")
public class UserService {
@Autowired
private IUser iUser;
public List<User> getAllUser() {
// TODO 自动生成的方法存根
return iUser.getAllUser();
}
public User getUserByID(int id) {
// TODO 自动生成的方法存根
return iUser.getUserByID(id);
}
public int deleteUserById(int id) {
// TODO 自动生成的方法存根
return iUser.deleteUserById(id);
}
public int updateUser(User user) {
// TODO 自动生成的方法存根
return iUser.updateUser(user);
}
}
Seven, multiple data source configuration
package com.yiibai.mybatis.datasource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.test2ds")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
Seven, web control class
Two controller classes are implemented here, UserController injects the Service class instance, and Ucontroller injects the JdbcTemplate class instance. code show as below:
package com.yiibai.mybatis.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.yiibai.mybatis.models.User;
import com.yiibai.mybatis.service.UserService;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
@Qualifier("userService") // @Resource(name = "userService")
private UserService userService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<User> getUsers() {
return userService.getAllUser();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUserByID(@PathVariable("id") int id) {
return userService.getUserByID(id);
}
}
The userService will use the default data source, which is the DataSource annotated with @Primary in DataSourceConfig
That is, the spring.test2ds (database test2) in application.yml.
package com.yiibai.mybatis.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.yiibai.mybatis.models.User;
import com.yiibai.mybatis.models.UserRowMapper;
@RestController
@RequestMapping("/u")
public class Ucontroller {
@Autowired
@Qualifier("primaryJdbcTemplate")
protected JdbcTemplate primaryJdbcTemplate;
@Autowired
@Qualifier("secondaryJdbcTemplate")
protected JdbcTemplate secondaryJdbcTemplate;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<User> getUsers() {
String sql = "SELECT * FROM user";
return primaryJdbcTemplate.query(sql, new UserRowMapper());
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUserByID(@PathVariable("id") int id) {
String sql= "SELECT * FROM user WHERE id = '"+id+"' ";
return secondaryJdbcTemplate.queryForObject(sql,new UserRowMapper());
}
}
Eight, the main category:
package com.yiibai.mybatis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringbootMutiDsApp implements EmbeddedServletContainerCustomizer{
public static void main(String[] args) {
SpringApplication.run(SpringbootMutiDsApp.class, args);
}
public void customize(ConfigurableEmbeddedServletContainer container) {
// TODO 自动生成的方法存根
container.setPort(8080);
}
}
9. Operation:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.8.RELEASE)
2017-11-01 09:02:22.233 INFO 5972 --- [ main] com.yiibai.mybatis.SpringbootMutiDsApp : Starting SpringbootMutiDsApp on mymotif-Vostro-14-5480 with PID 5972 (/home/mymotif/workspace/SpringBootTest/target/classes started by mymotif in /home/mymotif/workspace/SpringBootTest)
2017-11-01 09:02:22.314 INFO 5972 --- [ main] com.yiibai.mybatis.SpringbootMutiDsApp : No active profile set, falling back to default profiles: default
2017-11-01 09:02:22.458 INFO 5972 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@56de5251: startup date [Wed Nov 01 09:02:22 CST 2017]; root of context hierarchy
2017-11-01 09:02:26.092 INFO 5972 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-11-01 09:02:26.140 INFO 5972 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-11-01 09:02:26.141 INFO 5972 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-01 09:02:26.341 INFO 5972 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-11-01 09:02:26.341 INFO 5972 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3895 ms
2017-11-01 09:02:26.509 INFO 5972 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-01 09:02:26.514 INFO 5972 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-01 09:02:26.514 INFO 5972 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-01 09:02:26.515 INFO 5972 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-01 09:02:26.515 INFO 5972 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-01 09:02:27.587 INFO 5972 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@56de5251: startup date [Wed Nov 01 09:02:22 CST 2017]; root of context hierarchy
2017-11-01 09:02:27.676 INFO 5972 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/u/{id}],methods=[GET]}" onto public com.yiibai.mybatis.models.User com.yiibai.mybatis.web.Ucontroller.getUserByID(int)
2017-11-01 09:02:27.678 INFO 5972 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/u/list],methods=[GET]}" onto public java.util.List<com.yiibai.mybatis.models.User> com.yiibai.mybatis.web.Ucontroller.getUsers()
2017-11-01 09:02:27.679 INFO 5972 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/{id}],methods=[GET]}" onto public com.yiibai.mybatis.models.User com.yiibai.mybatis.web.UserController.getUserByID(int)
2017-11-01 09:02:27.680 INFO 5972 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/user/list],methods=[GET]}" onto public java.util.List<com.yiibai.mybatis.models.User> com.yiibai.mybatis.web.UserController.getUsers()
2017-11-01 09:02:27.685 INFO 5972 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-01 09:02:27.685 INFO 5972 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-01 09:02:27.718 INFO 5972 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-01 09:02:27.719 INFO 5972 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-01 09:02:27.759 INFO 5972 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-01 09:02:28.045 INFO 5972 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-11-01 09:02:28.230 INFO 5972 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-11-01 09:02:28.235 INFO 5972 --- [ main] com.yiibai.mybatis.SpringbootMutiDsApp : Started SpringbootMutiDsApp in 7.301 seconds (JVM running for 9.627)
http://localhost:8080/user/list
http://localhost:8080/u/list
Here it can be seen that http://localhost:8080/user/list obtains the user table data in the test2 library
And http://localhost:8080/u/list gets the user table data in the yiibai library (through primaryJdbcTemplate)
10. You can also write: Repository class injects JdbcTemplate class instance
package com.yiibai.mybatis.repositories;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.yiibai.mybatis.models.User;
import com.yiibai.mybatis.models.UserRowMapper;
@Repository
public class UserRepository {
@Autowired
@Qualifier("primaryJdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Transactional(readOnly = true)
public List<User> findAll() {
return jdbcTemplate.query("select * from user", new UserRowMapper());
}
@Transactional(readOnly = true)
public User findUserById(int id) {
return jdbcTemplate.queryForObject("select * from user where id=?", new Object[]{id}, new UserRowMapper());
}
}
Then the control class is changed to this:
package com.yiibai.mybatis.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.yiibai.mybatis.models.User;
import com.yiibai.mybatis.repositories.UserRepository;
@RestController
@RequestMapping("/u")
public class Ucontroller {
@Autowired
private UserRepository userRepository;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<User> getUsers() {
return userRepository.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getUserByID(@PathVariable("id") int id) {
return userRepository.findUserById(id);
}
}
refer to:
Configuration of SpringBoot multiple data sources (SpringBoot+MyBatis)
Usage example of jdbcTemplate in Spring (1)
Using mybatis to connect to the mysql database in Springboot
Spring Mybatis instance SqlSessionDaoSupport mixes xml configuration and annotation
The use of mybatis in Spring Boot