SpringBoot--集成mybatis映射框架
1 添加相关maven依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
2、application.properties(
application.yml
)
添加相关配置
spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username = root spring.datasource.password = 123456 #开启驼峰命名映射 mybatis.configuration.map-underscore-to-camel-case = true
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。
在启动类中添加对mapper包扫描@MapperScan
@SpringBootApplication @MapperScan("com.demo.dao.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
或者直接在Mapper类上面添加注解@Mapper
,建议使用上面那种,不然每个mapper加个注解也挺麻烦的
3、开发Mapper
第三步是最关键的一块,sql生产都在这里
import com.demo.model.Account; import org.apache.ibatis.annotations.Select; import java.util.List; public interface AccountMapper { @Select("SELECT * FROM account") List<Account> getAllAccounts(); @Select("SELECT * FROM account WHERE id = #{id}") Account getAccountById(Long id); }
4、使用
@Service public class ExampleServiceImpl { @Autowired//spring自动注入 private AccountMapper accountMapper; public List<Account> getAllAccounts() { return accountMapper.getAllAccounts(); } }