Purpose: To create a SpringBoot project and access the database
- step1
Create a SpringBoot project. When creating a SpringBoot project, check Spring Web, JDBC API, MySQL Driver, as shown in the following figure:
View the project poM file as follows:
Add two dependencies as follows:
<! -- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> < the groupId > org. Mybatis. Spring. The boot < / groupId > < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.3.2 < / version > </dependency> <! -- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> < artifactId > lombok < / artifactId > < version > 1.18.16 < / version > < scope > provided < / scope > < / dependency >Copy the code
- step2
Creating an entity Class
Entity classes need to correspond to table fields in the database, which are structured as follows
- step3
To configure the parameters, open the application.properties file and add the following configuration:
Spring. The datasource. The username = root spring. The datasource. The password = here to fill out your database password Spring. The datasource. Url = JDBC: mysql: / / localhost: 3306 / fill out your database name here? serverTimeZone=UTC&userUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.DriverCopy the code
- step4
Create a mapper interface as follows:
- step5
Create mapper interface corresponding XML file:
Note that the name of the XML file must have the same name as the Mapper interface
The content of the XML file must be in a certain format. For details, see the example on mybatis official website:Example XML format
The most important of these is the Namespace field, whose value is the path to the Mapper interface
- step6
Adding configuration items:
mybatis.type-aliases-package=com.nick.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
Copy the code
- step7
Test class validation:
Results:
- step8
The Controller to write:
Testing: