How to integrate Mybatis with SpingBoot
SpringBoot is a new framework from the Pivotal team designed to simplify the initial setup and development process for new Spring applications.
The main features of SpringBoot are:
- Create a stand-alone Spring application
- Embedded in Tomcat without the need to deploy a WAR file
- Simplifying Maven Configuration
- Automatic Spring configuration
- Provides production-ready functions such as metrics, health checks, and external configuration
- There is absolutely no code generation and no configuration requirements for XML
Setup of development environment
The requirements of the JDK
To use SpringBoot, you must use JDK1.8 or later.
The development tools
Eclipse and IDEA are the two most commonly used IDES for Java language development. Eclipse actually includes Eclipse, MyEclipse, and SpringTool Suite. The first two are very familiar. The Spring Tool Suite is eclipse customized for developing Spring applications, which is virtually indistinguishable from Eclipse or MyEclipse, and has features that make development easier. This article uses the Spring Tool Suite Tool. Spring Tool Suite (STS) Spring Tool Suite (STS) Version download. STS is a green version and can be used directly after decompression.
Maven requirements:
Apache-maven-3.3.9 or later is recommended for the project management tool. Now that we’re all set, how about we start with a try
There are only three steps required for SpringBoot to integrate Mybatis
- Step 1: Add dependencies;
- Step 2: Configure the data source.
- Step 3: Scan interface packets.
The detailed integration steps are as follows: reference database:
/* Springbootdb */ CREATE DATABASE /*! 32312 IF NOT EXISTS*/`springbootdb` /*! 40100 DEFAULT CHARACTER SET utf8 */; USE `springbootdb`; /* Create TABLE city*/ DROP TABLE IF EXISTS 'city'; CREATE TABLE 'city' (' id 'int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT' city ', 'provinceId' int(10) unsigned DEFAULT NULL COMMENT 'provinceId ',' cityName 'varchar(20) DEFAULT NULL COMMENT' cityName ', InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET= UTf8; /* insert into 'city' (' id ',' provinceId ',' cityName ',' description ') values (1,1,' Beijing ',' Beijing ' Beijing is the capital of China, the imperial capital for a hundred years, the political, economic and cultural center, and will be the center of the world.Zhengzhou is the capital of Henan province and the rising star of henan province Central city.'),(3,3,'ZhengZhou',' this guy is the capital of henan province, a rising star among cities, the political, economic and cultural center of henan province, and the central city of China.');Copy the code
Add dependencies; In addition to the regular dependencies, you need to add Mybatis and MySQL dependencies.
< the properties > < mybatis - spring - the boot > 1.2.0 < / mybatis - spring - the boot > < mysql connector - > 5.1.39 < / mysql - connector > < / properties > <dependencies> <! <dependency> <groupId>org.mybatis. Boot </groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot}</version> </dependency> <! --> <dependency> <groupId> MySQL </groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</version> </dependency> </dependencies>Copy the code
In the application.properties configuration file, configure the data source, Mybatis configuration, and mapping file.
# # data source configuration spring. The datasource. Url = JDBC: mysql: / / localhost: 3306 / library name spring. The datasource. The username = root Spring. The datasource. Password = root spring. The datasource. The driver - class - name = com. Mysql. JDBC. The driver package # # # Mybatis configuration entity is located, Names mybatis. TypeAliasesPackage = org. Spring. Springboot. # domain mapping file path where mybatis. MapperLocations = classpath: mapper / *. XMLCopy the code
Annotate the scan interface package on the main module using @mapperscan (” package name “).
@ SpringBootApplication / / Spring applications Boot logo @ MapperScan (" org. Spring. Springboot. Dao ") / / / / mapper interfaces scan package configuration if you want to display the Sql <logger name=" level="debug" /> public class Application {public static void main(String[] args) Springapplication. run(application. class,args); }}Copy the code
Congratulations on the fact that you’re on your way to achieving what you want, and we’ll move on.
entity
package com.zyz.entity; public class City { private Integer id; private Integer provinceId; private String cityName; private String description; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getProvinceId() { return provinceId; } public void setProvinceId(Integer provinceId) { this.provinceId = provinceId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public City(Integer id, Integer provinceId, String cityName, String description) { super(); this.id = id; this.provinceId = provinceId; this.cityName = cityName; this.description = description; } public City() { super(); } @Override public String toString() { return "City [id=" + id + ", provinceId=" + provinceId + ", cityName=" + cityName + ", description=" + description + "]"; }}Copy the code
dao
package com.zyz.dao;
import java.util.List;
import com.zyz.entity.City;
public interface CityDao {
public List<City> getall();
}
Copy the code
controller
package com.zyz.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.zyz.dao.CityDao; @RestController public class HelloController { @Autowired CityDao citydao; @RequestMapping("/hello") public String hello() { return ""+citydao.getall(); }}Copy the code
Project structure drawing
One last step is needed
Open our browser, launch our project, and visit
And when that happens, it means you’ve succeeded
The last
At the end of the article the author sorted out a lot of information for you! Including Java core knowledge + a full set of architect learning materials and video + first-line factory interview treasure dictionary + resume template interview ali Meituannetease Tencent Xiaomi IQiyi Quick hand bilibili bilibili interview questions +Spring source code collection +Java architecture actual combat e-books and so on! If in need of friends welcome to pay attention to the public number: future light, receive!