码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot--集成mybatis映射框架

时间:2020-03-14 20:00:48      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:dem   service   ibatis   enc   source   prope   under   span   依赖   

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();
    }
}

 

SpringBoot--集成mybatis映射框架

标签:dem   service   ibatis   enc   source   prope   under   span   依赖   

原文地址:https://www.cnblogs.com/jvStarBlog/p/12493776.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!