栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 数据访问

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 数据访问

一、数据访问的默认配置

1.引入jdbc开发场景

        
            org.springframework.boot
            spring-boot-starter-data-jdbc
        
        
            mysql
            mysql-connector-java
            5.1.49
        

相当于配置好了JdbcTemplate,HikariDataSource,Tx
2.添加配置项

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db3
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

此时就可以使用JdbcTemplate操作数据了

二、使用Druid作为数据源

将DruidDataSource注入容器便会替换默认数据源

@Configuration
public class DruidConfiguration {
    @Bean
    @ConfigurationProperties("spring.datasource")// 复用配置文件的数据源配置
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }
}
三、整合MyBatis
  • 引入mybatis场景启动器
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.4
        
  • 测试场景是否引入成功

1.Mapper接口

@Mapper
public interface UserMapper {

    public List findAll();
    @Select("select count(*) from user")
    public int findTotalCount();
}

2.Mapper.xml




    
        select * from user
    

3.测试方法

@Slf4j
@SpringBootTest
public class MainApplicationTest {

    @Autowired
    private UserMapper userMapper;
    @Test
    public void test4() {
        List users = userMapper.findAll();
        int totalCount = userMapper.findTotalCount();
        log.info("查询结果集:{}", users);
        log.info("总记录数为:{}", totalCount);
    }

四、配置MyBatis
mybatis:
# 指定mapper映射文件存放位置
  mapper-locations: classpath:boot/mappers/*.xml
# 开启驼峰命名
  configuration:
    map-underscore-to-camel-case: true
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/338161.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号