
2. 在配置文件中配置数据库连接信息:org.mybatis.spring.boot mybatis-spring-boot-starter2.1.3
# 服务端口
server:
port: 8080
# 配置数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ESP32DHT11?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: password
# springboot 整合mybatis的配置
mybatis:
# 配置别名
type-aliases-package: com.wyf.esp32dht11.pojo
# 配置mapper.xml文件的地址
mapper-locations: classpath:mybatis/mapper
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TempHumi {
private int id;
private String temp;
private String humi;
private Date dht11Date;
}
4. 创建Mapper接口
@Mapper // 该注解表示这是一个mybatis的Mapper类
@Repository
public interface TempHumiMapper {
int addTempHimi(TempHumi tempHumi);
}
如上所示,创建了一个Mapper接口,其中只有一个插入数据的方法!此处需要注意的是注解@Mapper,这个注解表示的该接口是一个mapper接口。当然,我们也可以使用包扫描的方式,将指定包下的所有接口扫描为mapper接口,如下所示:
@SpringBootApplication
@MapperScan("com.wyf.esp32dht11.mapper")
public class Esp32Dht11Application {
public static void main(String[] args) {
SpringApplication.run(Esp32Dht11Application.class, args);
}
}
以上两种注解方式都可以将接口作为mapper类,选择一种就好。
5. 创建Mapper接口所对应的mapper.xml文件6. 测试insert into `temp-humi`(temp,humi,dht11Date) values (#{temp},#{humi},#{dht11Date})
@Autowired
DataSource dataSource;
@Test
void dataSourceTest() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
@Autowired
private TempHumiMapper tempHumiMapper;
@Test
void addTempHuimData(){
TempHumi tempHumi = new TempHumi();
tempHumi.setTemp("30");
tempHumi.setHumi("77%");
tempHumi.setDht11Date(new Date(System.currentTimeMillis()));
int result = tempHumiMapper.addTempHimi(tempHumi);
System.out.println(result);
}