zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

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文件里配置的:

怎么使用事务

比如我们一个方法里需要分两次修改两张表的数据,怎么控制在一个事务呢?

如下:

 当然直接使用这个注解是无效的,我们还需要开启事务: