利用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;
}