1、Maven依赖
这里用到spring-boot-starter基础和spring-boot-starter-test用来做单元测试验证数据访问
引入连接mysql的必要依赖mysql-connector-java
引入整合MyBatis的核心依赖mybatis-spring-boot-starter
这里不引入spring-boot-starter-jdbc依赖,是由于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、在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建表语句
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、DAO层新建 UserDao,
@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、修改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("启动成功"); } }
6、重新启动