<1>SqlMapConfig.xml:mysql全局配置文件,配置了数据源,事务,运行环境等信息
mapper.xml:配置映射文件,sql语句
<2>SqlSessionFactory:会话工厂,用于创建SqlSession(会话),(通过执行器executor)用于操作数据库,底层
通过mapped statement对数据库存储封装,包括sql语句,输入参数,输出结果类型
·Executor:基本执行器和缓存执行器
<3>paramaterType,resultType
#{}:代表一个占位符,接受简单类型,可以为任意
${}:sql串,拼接符,接受简单类型只能写成${value},
selectOne与selectList
<4>自增主键的返回:
属性说明:
keyProperty:将查询到的主键值设置到paramterType指定对象的属性中
order: select LAST_INSERT_ID()相对于insert语句的执行顺序
resultType:指定select LAST_INSERT_ID()查询的结果类型
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
select LAST_INSERT_ID()
</selectKey>
insert语句中不需要写id字段
<5>非自增主键的返回(uuid())
<selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
select uuid()
</selectKey>
insert语句中必须写id字段
<6>mapper接口开发规范:
1.mapper.xml中namespace等于mapper接口地址(全路径)
2.mapper.java中的接口方法名和xml中的statement的id一致
3.输入参数类型和输出参数类型一致
代理对象的获取:UserMapper mapper=sqlSession.getMapper(UserMapper.class);
mapper调用selectOne或者selectList是根据接口的返回类型来确定的
<7>源码解析:
DefaultSqlSession类:
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
Configuration类:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
MapperRegistry类:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
MapperProxyFactory类:
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}