Spring Boot集成MyBatis
引入依赖
< dependency>
< groupId> org.mybatis.spring.boot</ groupId>
< artifactId> mybatis-spring-boot-starter</ artifactId>
< version> 1.3.2</ version>
</ dependency>
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> druid</ artifactId>
< version> 1.1.22</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 5.1.38</ version>
</ dependency>
编写配置文件:数据源、MyBatis配置
#数据源配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=root
#MyBatis配置
mybatis.mapper-locations=classpath:com/thrstones/mapper/*.xml
mybatis.type-aliases-package=com.thrstones.entity
在项目入口出加入映射扫描
@SpringBootApplication
@MapperScan ( "com.thrstones.dao" )
public class Application {
public static void main ( String[ ] args) {
SpringApplication. run ( Application. class ) ;
}
}
建表
create table account
(
id int auto_increment
primary key ,
name varchar ( 80 ) null ,
age int null ,
birthday date null
) ;
编写实体类
@Component
@ConfigurationProperties ( prefix = "account" )
public class Account {
private int id;
private String name;
private int age;
private Date birthday;
}
编写Dao接口、映射
public interface AccountDao {
public List< Account> findAll ( ) ;
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
< mapper namespace = " com.thrstones.dao.AccountDao" >
< select id = " findAll" resultType = " Account" >
select * from account
</ select>
</ mapper>
编写Service接口、和实现类
public interface AccountService {
public List< Account> findAll ( ) ;
}
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
@Resource
private AccountDao accountDao;
@Override
@Transactional ( propagation = Propagation. SUPPORTS)
public List< Account> findAll ( ) {
return accountDao. findAll ( ) ;
}
}
引入测试依赖、编写测试类
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-test</ artifactId>
< scope> test</ scope>
</ dependency>
@RunWith ( SpringRunner. class )
@SpringBootTest ( classes = Application. class )
public class TestService {
@Resource
private AccountService accountService;
@Test
public void test ( ) {
List< Account> accountList = accountService. findAll ( ) ;
accountList. forEach ( account - > System. out. println ( account) ) ;
}
}
测试结果