annotations包内存放着mybatis相关注解,下面列举下常用注解的用处
1. @ConstructorArgs + @Arg
作用:根据实体类的构造方法参数构造对象,具体使用方法可学习该篇博客。
https://blog.csdn.net/weixin_43866295/article/details/86594161
2. @AutomapConstructor
作用:为框架指定实体类的默认构造方法
public class AnnotatedSubject {
private final int id;
private final String name;
private final int age;
private final int height;
private final int weight;
public AnnotatedSubject(final int id, final String name, final int age, final int height, final int weight) {
this.id = id;
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
}
@AutomapConstructor
public AnnotatedSubject(final int id, final String name, final int age, final
Integer height, final Integer weight) {
this.id = id;
this.name = name;
this.age = age;
this.height = height == null ? 0 : height;
this.weight = weight == null ? 0 : weight;
}
}
3. @CacheNamespace+@Property
作用:配置一个缓存空间
对应xml配置为<cache />
Property属性用以给缓存中添加固定的数据
@CacheNamespace
public interface PersonMapper {
}
4.@CacheNamespaceRef
作用:使用一个现有的缓存空间
对应的xml配置为<cache-ref />
@CacheNamespaceRef(value = PersonMapper.class, name = "org.apache.ibatis.submitted.cache.PersonMapper")
private interface InvalidCacheNamespaceRefBothMapper {
}
5. @TypeDiscriminator + @Case
TypeDiscriminator 鉴别器
Case 鉴别条件
作用:根据case的鉴别条件返回指定的结果集映射
@TypeDiscriminator(
// target for test (ordinal number -> Enum constant)
column = "personType", javaType = PersonType.class, typeHandler = EnumOrdinalTypeHandler.class,
// Switch using enum constant name(PERSON or EMPLOYEE) at cases attribute
cases = {
@Case(value = "PERSON", type = Person.class, results = {@Result(property = "personType", column = "personType", typeHandler = EnumOrdinalTypeHandler.class)})
, @Case(value = "EMPLOYEE", type = Employee.class, results = {@Result(property = "personType", column = "personType", typeHandler = EnumOrdinalTypeHandler.class)})
})
@Select("SELECT id, firstName, lastName, personType FROM person WHERE id = #{id}")
Person findOneUsingTypeDiscriminator(int id);
6. @Delete+@Insert+@Update+@Select
作用: 注解模式的增删改查注解组
没什么好讲的
7.@DeleteProvider /@InsertProvider/@SelectProvider/@UpdateProvider
增删改查处理器
作用:提供增删改查的代码实现
参考类: SQLTest
@SelectProvider(type = BlogSqlProvider.class, method = "getSqlByTitle")
@ResultMap(value = "sqlBlogsMap")
// 这里调用resultMap,这个是SQL配置文件中的,必须该SQL配置文件与本接口有相同的全限定名
// 注意文件中的namespace路径必须是使用@resultMap的类路径
public List<Blog> getBlogByTitle(@Param("title")String title);
@InsertProvider(type = BlogSqlProvider.class, method = "insertSql")
public void insertBlog(Blog blog);
@UpdateProvider(type = BlogSqlProvider.class, method = "updateSql")
public void updateBlog(Blog blog);
@DeleteProvider(type = BlogSqlProvider.class, method = "deleteSql")
@Options(useCache = true, flushCache = false, timeout = 10000)
public void deleteBlog(int ids);
7. @flush
作用:定义在 Mapper 接口中的方法能够调用SqlSession#flushStatements() 方法。
8. @lang
语言驱动的注解
使用方式参照引用文章
https://www.jianshu.com/p/03642b807688
9. @Results+@Result+@Many+@One
返回结果集处理注解组
@Results:统一结果处理返回
@Result: 字段映射
@Many: 字段为一对多映射
@One:字段为一对一映射
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(column = "username", property = "username"),
@Result(property = "role", one = @One(resultMap = "org.apache.ibatis.submitted.annotion_many_one_add_resultmapid.RoleDao.roleMap2"))
})
public List<User> findAll();
10.@Mapper
标记这是个 Mapper 的注解,
在mybatis源码中并未进行使用,估计为配合mybatis-spring的mapperscan生成bean而存在【待验证】。
11. @Option
操作可选项
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
// 多Option注解配置
@Repeatable(Options.List.class)
public @interface Options {
/**
* The options for the {@link Options#flushCache()}.
* The default is {@link FlushCachePolicy#DEFAULT}
*/
enum FlushCachePolicy {
/** <code>false</code> for select statement; <code>true</code> for insert/update/delete statement. */
DEFAULT,
/** Flushes cache regardless of the statement type. */
TRUE,
/** Does not flush cache regardless of the statement type. */
FALSE
}
/**
* 是否使用二级缓存
*/
boolean useCache() default true;
/**
* 刷新缓存的策略
*/
FlushCachePolicy flushCache() default FlushCachePolicy.DEFAULT;
/**
* 返回类型
*/
ResultSetType resultSetType() default ResultSetType.DEFAULT;
/**
* 申明器类别
* STATEMENT:普通
* PREPARED:预编译
* CALLABLE:存储过程申明器
*/
StatementType statementType() default StatementType.PREPARED;
/**
* 加载数量
*/
int fetchSize() default -1;
/**
* 超时时间
*/
int timeout() default -1;
/**
* 设置主键自动生成
*/
boolean useGeneratedKeys() default false;
/**
* @return 主键在 Java 类中的属性
*/
String keyProperty() default "";
/**
* @return 主键在数据库中的字段
*/
String keyColumn() default "";
/**
* 设置返回结果集,参数名为结果集名称,多个结果集名称用“,”
隔开
*/
String resultSets() default "";
/**
* 配置对应的数据库id
*/
String databaseId() default "";
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface List {
Options[] value();
}
}
12. @Param
给参数定义名称
13. @SelectKey
返回非自增主键
如果我们数据库中的主键不是自增方式产生的,但是当我们插入新数据后,需要返回该条数据的主键,那么我们可以使用如下方法:
/**
* 保存新用户信息,并返回主键
*
* @param sysUser
* @return
*/
@Insert({"INSERT INTO sys_user (id,user_name, user_password,user_email,user_info, head_img, create_time)VALUES(#{id},#{userName},#{userPassword},#{userEmail},#{userInfo},#{headImg, jdbcType=BLOB},#{createTime,jdbcType=TIMESTAMP})"})
@SelectKey(statement="SELECT LAST_INSERT_ID()",
keyProperty="id",
resultType=Long.class,
before=false)
public int insert3(SysUser sysUser);
order属性的设置和使用的数据库有关。在MySQL数据库中,order属性设置的值是AFTER,因为当前记录的主键是在insert语句执行成功后才获取到的。而在Oracel数据库中,order属性的值要设置为BEFORE,这是因为Oracle数据库中需要先从序列获取值,然后将值作为主键插入到数据库中。
作者:开心跳蚤
链接:https://www.jianshu.com/p/b5f823ac5355。
14. @MapKey
作用:该注解用于返回Map格式的数据集合
使用说明:当我们试图使用Map来获取一个数据集合时,往往一个Map<String,Object>无法实现我们的需求,因为mybatis在解析返回值时,会把Map的Key值作为字段名,value作为字段值来返回,解决这个问题的方法就是在对应的方法上使用该标签,并再包裹一层Map,将指定的id字段作为key。
@MapKey("id")
public Map<Integer,Map<String,Object>> getNamesByIds(List<Map<String, Object>> list);
<select id="getNamesByIds" resultType="java.util.Map">
SELECT id, name FROM tb_abc WHERE id IN
<foreach item="item" collection="list" open="(" separator="," close=")">
#{item.id}
</foreach>
</select>