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

SpringBoot--集成mybatis映射框架
@SpringBootApplication
@MapperScan("com.demo.dao.mapper")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
SpringBoot--集成mybatis映射框架

或者直接在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();
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-11
  • 2021-07-06
  • 2022-12-23
  • 2018-06-20
  • 2022-12-23
  • 2023-03-09
猜你喜欢
  • 2021-04-16
  • 2021-05-17
  • 2021-04-17
  • 2021-12-17
  • 2022-12-23
  • 2021-06-11
  • 2022-12-23
相关资源
相似解决方案