使用mybatis里面的BaseMapper简化常规的数据操作
引入:
Gradle:
implementation 'tk.mybatis:mapper-spring-boot-starter:2.1.5'
包里面有一个接口类
BaseMapper
@tk.mybatis.mapper.annotation.RegisterMapper
public interface BaseMapper<T> extends
BaseSelectMapper<T>,
BaseInsertMapper<T>,
BaseUpdateMapper<T>,
BaseDeleteMapper<T> {
}
这里面继续了常见的增删改查的操作,实现它,就省去了定义常规的操作,对应resourcexiad 的xml文件也省了(如果有其它的操作,再加上去)
数据库信息:
CREATE TABLE `tache_info` (
`tch_id` BIGINT (20),
`tch_name` VARCHAR (1500),
`tch_type` VARCHAR (150)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `tache_info` (`tch_id`, `tch_name`, `tch_type`) VALUES('1','开始','es');
INSERT INTO `tache_info` (`tch_id`, `tch_name`, `tch_type`) VALUES('2','审核','json');
INSERT INTO `tache_info` (`tch_id`, `tch_name`, `tch_type`) VALUES('3','评估','mysql');
插入一些基本的数据
代码:
基础类:TacheInfo
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "tache_info")
public class TacheInfo {
/**
* @Id 设置主键,调用方法中ByPrimaryKey接口的时候用
*/
@Id
private Long tchId;
private String tchName;
private String tchType;
}
自定义注解:MyBatisRepository
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Component
public @interface MyBatisRepository {
String value() default "";
}
Mapper类继承:BaseMapper
@MyBatisRepository
public interface TacheInfoMapper extends BaseMapper<TacheInfo> {
}
服务类:TacheService
@Service
public class TacheService {
@Resource
private TacheInfoMapper tacheInfoMapper;
public List<TacheInfo> getTacheInfo(){
List<TacheInfo> tacheInfos = tacheInfoMapper.selectAll();
System.out.println(tacheInfos);
return tacheInfos;
}
public void addTacheInfo(TacheInfo tache){
tacheInfoMapper.insert(tache);
}
public void updateTacheInfo(TacheInfo tache){
tacheInfoMapper.updateByPrimaryKey(tache);
}
public TacheInfo getTacheInfoById(Long tchId) {
return tacheInfoMapper.selectByPrimaryKey(tchId);
}
public void delTacheInfo(Long tchId){
tacheInfoMapper.deleteByPrimaryKey(tchId);
}
}
测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class TestMyBatis {
@Resource
private TacheService tacheService;
@Test
public void getPath() {
String path = TestMyBatis.class.getResource("/").getPath();
System.out.println(path);
}
@Test
public void testGetAll() {
tacheService.getTacheInfo();
}
@Test
public void testAddTache() {
TacheInfo add = new TacheInfo(4L,"处理","add");
tacheService.addTacheInfo(add);
// 查看变化后的数据
tacheService.getTacheInfo();
}
@Test
public void testUpdateTache() {
Long tchId = 5L;
TacheInfo update = tacheService.getTacheInfoById(tchId);
System.out.println(update);
update.setTchName("更新");
update.setTchType("update");
tacheService.updateTacheInfo(update);
// 查看变化后的数据
tacheService.getTacheInfo();
}
@Test
public void testDelTache() {
Long tchId = 1L;
tacheService.delTacheInfo(tchId);
// 查看变化后的数据
tacheService.getTacheInfo();
}
}
注意:
如果是新建的项目,记得加上扫描的内容
@ComponentScan(value = "com.study")
@MapperScan(annotationClass = MyBatisRepository.class, basePackages = "com.study")
总结:
常见的数据操作,实现BaseMapper这个借口,很方便,也省去了些对应xml的工作。如果需要添加的时候,再进行添加就好。