22.怎们使用Mybatis操作数据库
2023-04-22 11:00:47 时间
Service层的基类
引入Mybatis-Plus的代码如下:
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency>
这个包依赖于mybatis-plus,mybatis-plus又依赖于mybatis-plus-extension:
mybatis-plus-extension中封装了一个Interface:
public interface IService<T> {}
我们自定义的Service层的接口需要继承IService,就可以调用IService中的实现。
IService中的实现在ServiceImpl类,ServiceImpl没有实现的就需要我们自定义Service类继承我们定义的Service层接口来自己实现,我们自定义的Service实现类需要继承ServiceImpl这个类:
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {}
ServiceImpl类中封装了很多数据库的增删改查基础操作,类似于EF的方式通过lamda表达式操作数据库,通过SQL语句操作数据库的方式。
Service层代码
我们需要定义一个接口继承IService:
public interface CategoryService extends IService<CategoryEntity> {}
定义一个类继承我们定义的接口和ServiceImpl:
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {}
调用Mybatis提供的默认的操作方法
以save方法为例:
@Autowired private CategoryService categoryService; categoryService.save(category);
lamda表达式的方式调用
我们在Service层实现这个方法:
@Override public void updateBrand(Long brandId, String name) { CategoryBrandRelationEntity categoryBrandRelationEntity=new CategoryBrandRelationEntity(); categoryBrandRelationEntity.setBrandId(brandId); categoryBrandRelationEntity.setBrandName(name); this.update(categoryBrandRelationEntity,new UpdateWrapper<CategoryBrandRelationEntity>().eq("brand_id",brandId)); }
update是ServiceImpl定义的方法,第一个参数是要更新的字段的实体,第二个字段是以lamda表达式的方式封装的where条件。
写SQL方式调用
我们在Service层实现这个方法:
@Override public void updateCategory(Long catId, String name) { this.baseMapper.updateCategory(catId,name); }
baseMapper是ServiceImpl类中DAO层基类的实例,我们实现我们的DAO层接口继承Mybatis提供的BaseMapper接口:
@Mapper public interface CategoryBrandRelationDao extends BaseMapper<CategoryBrandRelationEntity> { void updateCategory(@Param("catId") Long cat_id,@Param("name") String cat_name); }
DAO层的实现在mapper下的xml文件里配置的:
怎么使用事务
比如我们一个方法里需要分两次修改两张表的数据,怎么控制在一个事务呢?
如下:
当然直接使用这个注解是无效的,我们还需要开启事务:
相关文章
- restcontroller和controller区别
- api进阶Day3使用文件流对文件进行复制、使用块读写一组字节,使用byte数组提高读写的效率、返回当前时间。
- Mybatis框架--优化过程
- spring boot集成Elasticsearch-SpringBoot(25)
- 聊聊客户档案模型的设计与管理
- 国产时序数据库IotDB安装、与SpringBoot集成
- 一文说透kafka底层架构
- Java NIO全面详解(看这篇就够了)
- 使用多线程及线程池批量拷贝数据到MongoDB
- 用redis和jpa实现缓存文章和点击量-SpringBoot(23)
- JPA 入门实战(1)--简介
- 《Effective Java》第16条:要在仅有类中使用访问方法而非公有域
- springboot整合redis-SpringBoot(22)
- 网易二面:Kafka为什么吞吐量大、速度快??
- Springboot集成kafka高级应用实战
- 深入详解Mybatis的架构原理与6大核心流程
- redis-SpringBoot(21)
- 一步一图带你深入剖析 JDK NIO ByteBuffer 在不同字节序下的设计与实现
- 分库分表ShardingSphere-JDBC笔记整理
- Kafka消费消息丢失排查,原因竟是groupId重复