Mapper Example学习

Mapper Example学习

起因: 在公司实习时发现,公司所使用的Mybatis逆向工程生成的代码和Mapper.xml文件与自己常用的逆向工程生成器生成的不一样

公司Mybatis逆向工程生产以下产物

名称 描述 作用
XxxMapper.xml Mybatis配置文件 配置SQL语句
XxxMapper.class Mapper接口 对应每个SQL语句
XxxMapping.class 实体类 对应数据库表中的每个字段,一个实体类代表一行数据
XxxMappingExample.class SQL语句类 配置各种SQL条件

一、Mapper方法介绍:

方法名称 作用
int countByExample(XxxMappingExample example); 按条件计数
int deleteByExample(XxxMappingExample example); 按条件删除
int deleteByPrimaryKey(Integer id); 按主键删除
int insert(XxxMapping record); 插入一行数据
int insertSelective(XxxMapping record); 插入一行数据(某些字段可以为空)
List selectByExample(XxxMappingExample example); 按条件查询
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Spring 中,使用 MyBatis 进行数据库操作时,可以使用 `@Mapper` 注解标注 Mapper 接口,让 Spring 自动扫描并生成该接口的实现类,从而方便进行数据库操作。 具体来说,`@Mapper` 注解是一个组合注解,包含了 `@Component` 和 `@MapperScan` 两个注解的功能。其中,`@Component` 注解将 Mapper 接口标记为一个 Spring 组件,使其能够被 Spring 扫描并加入到 IoC 容器中;`@MapperScan` 注解用于指定扫描 Mapper 接口的包路径。 `@Mapper` 注解的实现原理主要依赖于 Spring 的 BeanPostProcessor 接口和 JDK 的动态代理技术。当 Spring 扫描到一个被 `@Mapper` 注解标注的 Mapper 接口时,会生成该接口的代理类并加入到 IoC 容器中。该代理类会拦截接口中的方法调用,并将其转发给 MyBatisSqlSession 完成具体的数据库操作。 下面是 `@Mapper` 注解的部分源码: ```java @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented @Component public @interface Mapper { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any (or empty String otherwise) */ String value() default ""; } ``` 可以看到,`@Mapper` 注解中除了包含 `@Component` 注解的功能外,还定义了一个 `value()` 方法,用于指定该组件在 Spring IoC 容器中的名称。 需要注意的是,使用 `@Mapper` 注解自动扫描 Mapper 接口的功能需要在 Spring 的配置文件中添加 `@MapperScan` 注解。例如: ```java @Configuration @MapperScan("com.example.mapper") public class MybatisConfig { // ... } ``` 其中,`@MapperScan` 注解的参数为 Mapper 接口所在的包路径。这样,Spring 在启动时会自动扫描该包下的 Mapper 接口,并生成其实现类并加入到 IoC 容器中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值