目录
二、XMLConfigBuilder (放入扫描注解工具方法)
一、手把手教你写个Mybatis框架
上文:https://blog.youkuaiyun.com/ls490447406/article/details/105598980
二、支持注解形式进行数据库交互
一、Mybatis-config (开启注解扫描)
<mappers>
<!-- 使用xml-->
<!--<mapper resource="com/lishuo/dao/IUserDao.xml"/>-->
<!-- 使用注解 -->
<mapper class="com.lishuo.dao.IUserDao"/>
</mappers>
二、XMLConfigBuilder (放入扫描注解工具方法)
private static Map<String, Mapper> loadMapperAnnotation(String daoClassPath) throws Exception {
// 定义返回值对象
Map<String, Mapper> mappers = new HashMap<String, Mapper>();
// 1.得到dao接口的字节码对象
Class daoClass = Class.forName(daoClassPath);
// 2.得到dao接口中的方法数组
Method[] methods = daoClass.getMethods();
// 3.遍历Method数组
for (Method method : methods) {
// 取出每一个方法,判断是否有select注解
boolean isAnnotated = method.isAnnotationPresent(Select.class);
if (isAnnotated) {
// 创建Mapper对象
Mapper mapper = new Mapper();
// 取出注解的value属性值
Select selectAnno = method.getAnnotation(Select.class);
String queryString = selectAnno.value();
mapper.setQueryString(queryString);
// 获取当前方法的返回值,还要求必须带有泛型信息
Type type = method.getGenericReturnType();
// 判断type是不是参数化的类型
if (type instanceof ParameterizedType) {
// 强转
ParameterizedType ptype = (ParameterizedType) type;
// 得到参数化类型中的实际类型参数
Type[] types = ptype.getActualTypeArguments();
// 取出第一个
Class domainClass = (Class) types[0];
// 获取domainClass的类名
String resultType = domainClass.getName();
// 给Mapper赋值
mapper.setResultType(resultType);
}
// 组装key的信息
// 获取方法的名称
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className + "." + methodName;
// 给map赋值
mappers.put(key, mapper);
}
}
return mappers;
}
三、定义注解-支持手写Sql
@Documented
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Service
public @interface Select {
String value();
}
四、XMLConfigBuilder 开启注解扫描
- 上篇文章已经有详细得解释,本处只是给注释代码放出
} else {
System.out.println("使用的是注解");
// 表示没有resource属性,用的是注解
// 获取class属性的值
String daoClassPath = mapperElement.attributeValue("class");
// 根据daoClassPath获取封装的必要信息
Map<String, Mapper> mappers = loadMapperAnnotation(daoClassPath);
// 给configuration中的mappers赋值
cfg.setMappers(mappers);
}
五、IUserDao 加入注解 并写入执行Sql
package com.lishuo.dao;
import com.lishuo.annotation.Select;
import com.lishuo.pojo.User;
import java.util.List;
public interface IUserDao {
@Select("select * from user")
List<User> findAll();
}