Spring boot集成mybatis
maven依賴
我的spring boot版本是2.5.0,集成mybatis,首先需要數據庫的支持,這里我選擇mysql數據庫,版本是8.0.11,然后使用druid連接池,其次就需要加上mybatis的依賴。
<!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><!--druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.4</version></dependency><!--myabtis-springboot--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency>
yml配置
yml中配置了數據源和mybatis的配置
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=trueusername: rootpassword: 123456
# mybatis配置
mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: org.syx.dts.entityconfiguration:map-underscore-to-camel-case: true
項目結構
entity包放的是定義的實體,mapper包是各mapper的接口,resources下的mapper放的是mybatis的xml
mapper注解
啟動類上的MapperScan(“org.syx.dts.mapper”)這個注解可寫可不寫。主要看mapper接口有沒有加@Mapper注解,加了,啟動類就不需要加MapperScan,當然你加了也無所謂。
各類展示
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DailyReport {private Integer id;private Integer empTotal;private Integer deviceTotal;private Integer deviceUsedNum;private Integer birthdayEmpNum;@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime createTime;
}
@Mapper
public interface DailyReportMapper {@Select("insert into daily_report(emp_total,device_total,device_used_num,birthday_emp_num,create_time) values(#{empTotal},#{deviceTotal},#{deviceUsedNum},#{birthdayEmpNum},NOW())")void save(DailyReport dailyReport);@Select("select * from daily_report")List<DailyReport> lists();
}
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.syx.dts.mapper.DeviceMapper"><insert id="batchSave">INSERT INTO `device` (name,no,description,type,create_time,status) VALUES<!-- 使用foreach遍歷列表 --><foreach item="device" index="index" collection="list" separator=",">(#{device.name}, #{device.no}, #{device.description}, #{device.type}, NOW(),0)</foreach></insert><update id="update">update `device` set<if test="status != null and status != ''">status = #{status}</if>where id = #{id}</update><select id="getDeviceList" resultType="org.syx.dts.entity.Device">select id,name,no,description,type,create_time,status from `device` where 1=1<if test="name != null and name != ''">AND name LIKE CONCAT('%', #{name}, '%')</if><if test="flag != null ">AND status = #{flag}</if></select>
</mapper>
總結
如此,Spring boot集成mybatis就完成了,整個過程是非常簡單的。