zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    TFTP服务器的使用
    SecureCRT Ver 8.1.4 整合汉化绿色版一体包
    SecureCRT Ver 8.1.4 整合汉化绿色版一体包
    深度好贴,mark一下!
    DataSnap——利用TParams进行多表事务更新
    临时表经典使用范例
    PHP对文件的操作方法
    中国银行支付接口(ecshop版)
    常用支付接口实例php版
    PHPCMS网站二次开发配置要点
  • 原文地址:https://www.cnblogs.com/jvStarBlog/p/12493776.html
Copyright © 2011-2022 走看看