Spring boot整合mybatis(最小配置)
- 创建maven工程、导入坐标
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
- 配置属性:连接mysql、redis、mybatis
spring:
datasource:
url: jdbc:mysql://192.168.5.128/db1
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
redis:
host: 192.168.5.128
port: 6379
password: 123456
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-packge: com.yx.domain
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 编码:启动类、三层架构、测试类
package com.yx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MybatisApp {
public static void main(String[] args) {
SpringApplication.run(MybatisApp.class,args);
}
}
@Data
public class Stu {
private Integer id;
private String name;
private Integer age;
}
package com.yx.mapper;
import com.yx.domain.Stu;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface StuMapper {
@Select("select * from stu")
public List<Stu> findAll();
}
package com.yx;
import com.yx.domain.Stu;
import com.yx.mapper.StuMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MybatisApp.class)
public class StuTest {
@Autowired
private StuMapper mapper;
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testAll(){
List<Stu> all = mapper.findAll();
System.out.println(all);
System.out.println(redisTemplate);
}
}