利用SpringBoot整合MyBatis实战记录

利用SpringBoot整合MyBatis实战记录


一、MyBatis是什么?

MyBatis是一个非常方便易用的持久层框架,利用它可以实现服务端和后台数据库的交互,在springboot的整合中,它一般以注解的形式出现使用。

二、使用步骤

1.导入maven依赖

代码如下(示例):

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.3</version>
		</dependency>

可以在application.properties中配置:
logging.level.com.hyh.springboot.mapper = debug
可以监控输入的sql语句

2.建立Mapper接口,绑定sql语句和对应函数

在主程序入口先添加一行配置:@MapperScan(“com.hyh.springboot.mapper”)
代码如下(示例):

@Mapper
public interface MyBatisMapper {
    //@Select("select * from dht11 where t>#{str} order by t ASC")
    @Select("select temperature,humidity,smog,time from dht11 order by time ASC")
    public List<Dht11> get();
    @Update("insert into dht11(temperature,humidity,smog,time) values(#{temperature},#{humidity},#{smog},#{time})")
    public void save(Dht11 dht11);
}

该处涉及到查询和添加,tips:在sql语句中尽量不要使用*,对于较大数量的数据来说,影响查询的速度。

3.在Dao层中调用函数,实现数据交互功能

**查询:**
    @Autowired
    MyBatisMapper myBatisMapper;
    public List<Dht11> getDao() {
        List<Dht11> list1 = redisTemplate.opsForList().range("dhtlist",0,-1);
        if(list1.size() != 0){
            return list1;
        }
        List<Dht11> list = myBatisMapper.get();
        redisTemplate.opsForList().rightPushAll("dhtlist",list);
        return list;
    }
**保存:**
    public Dht11 saveDao(Dht11 dht11) {
        redisTemplate.opsForList().rightPush("dhtlist",dht11);
        myBatisMapper.save(dht11);
        return dht11;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值