1. Maven dependencies
The spring-boot-starter foundation and spring-boot-starter-test are used here for unit testing to verify data access.
Introducing the necessary dependencies for connecting to mysql mysql-connector-java
Introducing the core dependencies of integrating MyBatis mybatis-spring-boot-starter
here The spring-boot-starter-jdbc dependency is not introduced because this dependency is already included in mybatis-spring-boot-starter
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency> <!-- 数据库 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
2. Add database information in application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/datalar
spring.datasource.username=root
spring.datasource.password=654321
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3. MySQL table creation statement
CREATE TABLE userinfo (
id INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) DEFAULT NULL,
age VARCHAR(20) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
4. Create a new UserDao in the DAO layer,
@Mapper
public interface UserDao {
@Select("SELECT * FROM USERINFO WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USERINFO(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
5. Modify application.java
@EnableAutoConfiguration @MapperScan("com.lar.testInterface.dao") @ComponentScan(basePackages= {"com.lar.testInterface"}) public class Application { public static void main(String[] args) throws Exception{ SpringApplication.run(Application.class, args); System.out.println("Startup successful"); } }
6. Restart