pom文件
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
yml配置
mapper:
mappers: com.huaqing.common.constant.TKMapper,tk.mybatis.mapper.common.Mapper,tk.mybatis.mapper.common.MySqlMapper
# 设置 insert 和 update 中,是否判断字符串类型不等于空
not-empty: true
启动类注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@MapperScan(basePackages = "com.water.*.mapper")
@SpringBootApplication
public class WaterApplication {
public static void main(String[] args) {
SpringApplication.run(WaterApplication.class, args);
}
}
通用类
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface TKMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
实体对象
/**
* 使用@Table注解标明对应的数据库表
*/
@Data
@Table(name = "equipments")
public class Equipments implements Serializable {
private static final long serialVersionUID = -79337100357175395L;
/**
* 使用@Id注解,标明对应的主键id
*/
@Id
private Long id;
/**
* 设备名称
*/
private String equipName;
/**
* 安装时间,使用@JsonFormat对日期进行规范
*/
@JsonFormat(pattern = "yyyy-MM-dd")
private Date installAt;
/**
* 以下6个字段是数据库基本数据,可以提取到BaseEntity实体类中
*/
/**
* 创建者
*/
private String createBy;
/**
* 创建时间
*/
private Date createAt;
/**
* 修改者
*/
private String modifyBy;
/**
* 修改时间
*/
private Date modifyAt;
/**
* 设备状态位
*/
private Integer status;
/**
* 设备删除位
*/
private Integer delFlag;
/**
* 搜索条件使用@Transient表示该字段不进行数据库通信
*/
@Transient
private String condition;
}
mapper接口
/**
* 设备表(Equipments)表数据库访问层,使用@Repository注解并继承Mapper类
*/
@Repository
public interface EquipmentsMapper extends TKMapper<Equipments> {
}
service接口
/**
* 设备表(Equipments)表服务接口
*/
public interface EquipmentsService {
/**
* 查询多条数据
* @param equipments 设备条件
* @return 对象列表
*/
List<Equipments> queryAll(Equipments equipments);
}
service实现类
/**
* 设备表(Equipments)表服务实现类
*/
@Service
public class EquipmentsServiceImpl implements EquipmentsService {
@Resource
EquipmentsMapper equipmentsMapper;
/**
* 查询多条数据
*
* @param equipments 条件查询集合
* @return 对象列表
*/
@Override
public List<Equipments> queryAll(Equipments equipments) {
Example example = new Example(Equipments.class);
Example.Criteria criteria = example.createCriteria();
//模糊查询
if (equipments.getCondition()!=null){
criteria.andLike("equipName", "%" + equipments.getCondition() + "%");
}
//相等条件
criteria.andEqualTo("status", equipments.getStatus())
.andEqualTo("delFlag", 0)
.andEqualTo("id", equipments.getId());
//条件查询
return equipmentsMapper.selectByExample(example);
}
}