基于xml配置
1.目录
2.代码展示
User
package com.cjy.bean;
import java.sql.Date;
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public User() {
}
public User(Integer id, String username, Date birthday, String sex, String address) {
this.id = id;
this.username = username;
this.birthday = birthday;
this.sex = sex;
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
IUserDao
package com.cjy.dao;
import com.cjy.bean.User;
import java.util.List;
public interface IUserDao {
List<User> findAll();
}
Configuration
package com.cjy.mybatis;
import java.util.HashMap;
import java.util.Map;
/**
* 配置类,
* 配置连接数据库的driver,url,username,password
* 配置mappers,key代表dao接口的类路径,value代表存储的是sql语句和返回对象类型
*/
public class Configuration {
private Map<String,Mapper> mappers=new HashMap<String, Mapper>();//不new会报空指针异常
private String url;
private String driver;
private String username;
private String password;
public Configuration() {
}
public Map<String, Mapper> getMappers() {
return mappers;
}
public void setMappers(Map<String, Mapper> mappers) {
this.mappers.putAll(mappers);//可以有多个mapper,避免被覆盖
}
public Configuration(String url, String driver, String username, String password) {
this.url = url;
this.driver = driver;
this.username = username;
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DataSourceUtils
package com.cjy.mybatis;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* DataSourceUtils是获取configuration的driver,url,username,password来连接数据库
*/
public class DataSourceUtils {
public static Connection getConnection(Configuration configuration) throws SQLException, ClassNotFoundException {
Class.forName(configuration.getDriver());
Connection connection=DriverManager.getConnection(configuration.getUrl(),configuration.getUsername(),configuration.getPassword());
return connection;
}
}
DefaultSqlSession
package com.cjy.mybatis;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
/**
* DefaultSqlSession实现SqlSession接口
* sqlSession连接数据库,获得交互信息
* sqlSession的getMapper方法来获取接口的代理对象
*/
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
private Connection connection;
public DefaultSqlSession(Configuration configuration) throws SQLException, ClassNotFoundException {
this.configuration = configuration;
this.connection=DataSourceUtils.getConnection(configuration);
}
public <T> T getMapper(Class<T> daoInterfaceClass) {
T daoProxy=(T)Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),new Class[]{daoInterfaceClass},
new MapperProxyFactory(configuration.getMappers(),connection));
return daoProxy;
}
public void close() throws SQLException {
connection.close();
}
}
DefaultSqlSessionFactory
package com.cjy.mybatis;
import java.sql.SQLException;
/**
* DefaultSqlSessionFactory实现SqlSessionFactory接口
* openSession方法生成sqlSession对象
*/
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration=configuration;
}
public SqlSession openSession() throws SQLException, ClassNotFoundException {
return new DefaultSqlSession(configuration);
}
}
Executor
package com.cjy.mybatis;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* selectList方法负责执行SQL语句,并且封装结果集
*/
public class Executor {
public <E> List<E> selectList(Mapper mapper, Connection conn) {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
//1.取出mapper中的数据
String queryString = mapper.getQueryString();//select * from user
String resultType = mapper.getResultType();//com.itheima.domain.User
Class domainClass = Class.forName(resultType);
//2.获取PreparedStatement对象
pstm = conn.prepareStatement(queryString);
//3.执行SQL语句,获取结果集
rs = pstm.executeQuery();
//4.封装结果集
List<E> list = new ArrayList<E>();//定义返回值
while(rs.next()) {
//实例化要封装的实体类对象
E obj = (E)domainClass.newInstance();
//取出结果集的元信息:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
//取出总列数
int columnCount = rsmd.getColumnCount();
//遍历总列数
for (int i = 1; i <= columnCount; i++) {
//获取每列的名称,列名的序号是从1开始的
String columnName = rsmd.getColumnName(i);
//根据得到列名,获取每列的值
Object columnValue = rs.getObject(columnName);
//给obj赋值:使用Java内省机制(借助PropertyDescriptor实现属性的封装)
PropertyDescriptor pd = new PropertyDescriptor(columnName,domainClass);//要求:实体类的属性和数据库表的列名保持一种
//获取它的写入方法
Method writeMethod = pd.getWriteMethod();
//把获取的列的值,给对象赋值
writeMethod.invoke(obj,columnValue);
}
//把赋好值的对象加入到集合中
list.add(obj);
}
return list;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
release(pstm,rs);
}
}
private void release(PreparedStatement pstm,ResultSet rs){
if(rs != null){
try {
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(pstm != null){
try {
pstm.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Mapper
package com.cjy.mybatis;
/**
* mapper存储的是(sql语句,返回对象的类型)
*/
public class Mapper {
private String queryString;
private String resultType;
public String getQueryString() {
return queryString;
}
public String getResultType() {
return resultType;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
}
MapperProxyFactory
package com.cjy.mybatis;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;
/**
* MapperProxyFactory对象实现InvocationHandler接口
* invoke方法判断被代理对象的全限定类名和解析配置文件的全限定类型是否一致,
* 从而判断是否执行executor的selectList方法
*/
public class MapperProxyFactory implements InvocationHandler {
private Map<String,Mapper> mappers;
private Connection connection;
public MapperProxyFactory(Map<String, Mapper> mappers, Connection connection) {
this.mappers=mappers;
this.connection=connection;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key=className+"."+methodName;
System.out.println(mappers.get(key));
if(mappers.get(key)==null){
throw new RuntimeException("sql配置文件有误");
}
return new Executor().selectList(mappers.get(key),connection);
}
}
Resources
package com.cjy.mybatis;
import java.io.InputStream;
public class Resources {
/**
* 使用类加载器读取配置文件
* @param xmlPath 配置文件的路径
* @return
*/
public static InputStream getResourceAsStream(String xmlPath) {
return Resources.class.getClassLoader().getResourceAsStream(xmlPath);
}
}
SqlSession
package com.cjy.mybatis;
import java.sql.SQLException;
/**
* sqlSession接口,用于获得接口的代理对象
*/
public interface SqlSession {
<T> T getMapper(Class<T> daoInterfaceClass);
public void close() throws SQLException;
}
SqlSessionFactory
package com.cjy.mybatis;
import java.sql.SQLException;
/**
* sqlSessionFactory接口,用于生成sqlSession对象
*/
public interface SqlSessionFactory {
SqlSession openSession() throws SQLException, ClassNotFoundException;
}
SqlSessionFactoryBuilder
package com.cjy.mybatis;
import java.io.InputStream;
/**
* SqlSessionFactoryBuilder,其build方法用于生成sqlSessionFactory对象
*/
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream in){
Configuration configuration = XMLConfigBuilder.loadConfiguration(in);
return new DefaultSqlSessionFactory(configuration);
}
}
XMLConfigBuilder
package com.cjy.mybatis;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 用于解析配置文件
*/
public class XMLConfigBuilder {
/**
* 解析主配置文件,把里面的内容填充到DefaultSqlSession所需要的地方
* 使用的技术:
* dom4j+xpath
*/
public static Configuration loadConfiguration(InputStream config){
try{
//定义封装连接信息的配置对象(mybatis的配置对象)
Configuration cfg = new Configuration();
//1.获取SAXReader对象
SAXReader reader = new SAXReader();
//2.根据字节输入流获取Document对象
Document document = reader.read(config);
//3.获取根节点
Element root = document.getRootElement();
//4.使用xpath中选择指定节点的方式,获取所有property节点
List<Element> propertyElements = root.selectNodes("//property");
//5.遍历节点
for(Element propertyElement : propertyElements){
//判断节点是连接数据库的哪部分信息
//取出name属性的值
String name = propertyElement.attributeValue("name");
if("driver".equals(name)){
//表示驱动
//获取property标签value属性的值
String driver = propertyElement.attributeValue("value");
cfg.setDriver(driver);
}
if("url".equals(name)){
//表示连接字符串
//获取property标签value属性的值
String url = propertyElement.attributeValue("value");
cfg.setUrl(url);
}
if("username".equals(name)){
//表示用户名
//获取property标签value属性的值
String username = propertyElement.attributeValue("value");
cfg.setUsername(username);
}
if("password".equals(name)){
//表示密码
//获取property标签value属性的值
String password = propertyElement.attributeValue("value");
cfg.setPassword(password);
}
}
//取出mappers中的所有mapper标签,判断他们使用了resource还是class属性
List<Element> mapperElements = root.selectNodes("//mappers/mapper");
//遍历集合
for(Element mapperElement : mapperElements){
//判断mapperElement使用的是哪个属性
Attribute attribute = mapperElement.attribute("resource");
if(attribute != null){
System.out.println("使用的是XML");
//表示有resource属性,用的是XML
//取出属性的值
String mapperPath = attribute.getValue();//获取属性的值"com/itheima/dao/IUserDao.xml"
//把映射配置文件的内容获取出来,封装成一个map
Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath);
//给configuration中的mappers赋值
cfg.setMappers(mappers);
}else{
// System.out.println("使用的是注解");
// //表示没有resource属性,用的是注解
// //获取class属性的值
// String daoClassPath = mapperElement.attributeValue("class");
// //根据daoClassPath获取封装的必要信息
// Map<String,Mapper> mappers = loadMapperAnnotation(daoClassPath);
// //给configuration中的mappers赋值
// cfg.setMappers(mappers);
}
}
//返回Configuration
return cfg;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
try {
config.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 根据传入的参数,解析XML,并且封装到Map中
* @param mapperPath 映射配置文件的位置
* @return map中包含了获取的唯一标识(key是由dao的全限定类名和方法名组成)
* 以及执行所需的必要信息(value是一个Mapper对象,里面存放的是执行的SQL语句和要封装的实体类全限定类名)
*/
private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
InputStream in = null;
try{
//定义返回值对象
Map<String,Mapper> mappers = new HashMap<String,Mapper>();
//1.根据路径获取字节输入流
in = Resources.getResourceAsStream(mapperPath);
//2.根据字节输入流获取Document对象
SAXReader reader = new SAXReader();
Document document = reader.read(in);
//3.获取根节点
Element root = document.getRootElement();
//4.获取根节点的namespace属性取值
String namespace = root.attributeValue("namespace");//是组成map中key的部分
//5.获取所有的select节点
List<Element> selectElements = root.selectNodes("//select");
//6.遍历select节点集合
for(Element selectElement : selectElements){
//取出id属性的值 组成map中key的部分
String id = selectElement.attributeValue("id");
//取出resultType属性的值 组成map中value的部分
String resultType = selectElement.attributeValue("resultType");
//取出文本内容 组成map中value的部分
String queryString = selectElement.getText();
//创建Key
String key = namespace+"."+id;
//创建Value
Mapper mapper = new Mapper();
mapper.setQueryString(queryString);
mapper.setResultType(resultType);
//把key和value存入mappers中
mappers.put(key,mapper);
}
return mappers;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
in.close();
}
}
/**
* 根据传入的参数,得到dao中所有被select注解标注的方法。
* 根据方法名称和类名,以及方法上注解value属性的值,组成Mapper的必要信息
* @param daoClassPath
* @return
*/
// 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();//List<User>
// //判断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;
// }
}
IUserDao.xml
<mapper namespace="com.cjy.dao.IUserDao">
<select id="findAll" resultType="com.cjy.bean.User">
select * from users
</select>
</mapper>
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 配置mybatis的环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源信息-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/cjy"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--配置映射信息-->
<mappers>
<mapper resource="com/cjy/dao/IUserDao.xml"></mapper>
<!-- <mapper class="com.cjy.dao.IUserDao"></mapper>-->
</mappers>
</configuration>
MybatisTest
import com.cjy.bean.User;
import com.cjy.dao.IUserDao;
import com.cjy.mybatis.Resources;
import com.cjy.mybatis.SqlSession;
import com.cjy.mybatis.SqlSessionFactory;
import com.cjy.mybatis.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
public class MybatisTest {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//1.读取配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建sqlSessionFactoryBuilder构建者对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//3.创建sqlSessionFactory对象(根据inputStream和sqlSessionFactoryBuilder)
SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(resourceAsStream);
//4.创建session对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//5.创建dao接口的mapper代理对象
IUserDao mapper = sqlSession.getMapper(IUserDao.class);
//6.执行方法
List<User> all = mapper.findAll();
for(User user:all){
System.out.println(user);
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>mybatisSelfDefined</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!--日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--xml解析 dom4j-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- dom4j 的依赖包 jaxen -->
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
</project>
基于注解配置
1.目录
与xml配置相比,新加入了Select类,改变了IUserDao、SqlMapConfig.xml、XMLConfigBuilder,去掉了IUserdao.xml
2.改变的代码
Select
package com.cjy.mybatis;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select {
String value();
}
IUserDao
package com.cjy.dao;
import com.cjy.bean.User;
import com.cjy.mybatis.Select;
import java.util.List;
public interface IUserDao {
@Select("select * from users")
List<User> findAll();
}
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 配置mybatis的环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源信息-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/cjy"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--配置映射信息-->
<mappers>
<!-- <mapper resource="com/cjy/dao/IUserDao.xml"></mapper>-->
<mapper class="com.cjy.dao.IUserDao"></mapper>
</mappers>
</configuration>
XMLConfigBuilder
package com.cjy.mybatis;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 用于解析配置文件
*/
public class XMLConfigBuilder {
/**
* 解析主配置文件,把里面的内容填充到DefaultSqlSession所需要的地方
* 使用的技术:
* dom4j+xpath
*/
public static Configuration loadConfiguration(InputStream config){
try{
//定义封装连接信息的配置对象(mybatis的配置对象)
Configuration cfg = new Configuration();
//1.获取SAXReader对象
SAXReader reader = new SAXReader();
//2.根据字节输入流获取Document对象
Document document = reader.read(config);
//3.获取根节点
Element root = document.getRootElement();
//4.使用xpath中选择指定节点的方式,获取所有property节点
List<Element> propertyElements = root.selectNodes("//property");
//5.遍历节点
for(Element propertyElement : propertyElements){
//判断节点是连接数据库的哪部分信息
//取出name属性的值
String name = propertyElement.attributeValue("name");
if("driver".equals(name)){
//表示驱动
//获取property标签value属性的值
String driver = propertyElement.attributeValue("value");
cfg.setDriver(driver);
}
if("url".equals(name)){
//表示连接字符串
//获取property标签value属性的值
String url = propertyElement.attributeValue("value");
cfg.setUrl(url);
}
if("username".equals(name)){
//表示用户名
//获取property标签value属性的值
String username = propertyElement.attributeValue("value");
cfg.setUsername(username);
}
if("password".equals(name)){
//表示密码
//获取property标签value属性的值
String password = propertyElement.attributeValue("value");
cfg.setPassword(password);
}
}
//取出mappers中的所有mapper标签,判断他们使用了resource还是class属性
List<Element> mapperElements = root.selectNodes("//mappers/mapper");
//遍历集合
for(Element mapperElement : mapperElements){
//判断mapperElement使用的是哪个属性
Attribute attribute = mapperElement.attribute("resource");
if(attribute != null){
System.out.println("使用的是XML");
//表示有resource属性,用的是XML
//取出属性的值
String mapperPath = attribute.getValue();//获取属性的值"com/itheima/dao/IUserDao.xml"
//把映射配置文件的内容获取出来,封装成一个map
Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath);
//给configuration中的mappers赋值
cfg.setMappers(mappers);
}else{
System.out.println("使用的是注解");
//表示没有resource属性,用的是注解
//获取class属性的值
String daoClassPath = mapperElement.attributeValue("class");
//根据daoClassPath获取封装的必要信息
Map<String,Mapper> mappers = loadMapperAnnotation(daoClassPath);
//给configuration中的mappers赋值
cfg.setMappers(mappers);
}
}
//返回Configuration
return cfg;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
try {
config.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 根据传入的参数,解析XML,并且封装到Map中
* @param mapperPath 映射配置文件的位置
* @return map中包含了获取的唯一标识(key是由dao的全限定类名和方法名组成)
* 以及执行所需的必要信息(value是一个Mapper对象,里面存放的是执行的SQL语句和要封装的实体类全限定类名)
*/
private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
InputStream in = null;
try{
//定义返回值对象
Map<String,Mapper> mappers = new HashMap<String,Mapper>();
//1.根据路径获取字节输入流
in = Resources.getResourceAsStream(mapperPath);
//2.根据字节输入流获取Document对象
SAXReader reader = new SAXReader();
Document document = reader.read(in);
//3.获取根节点
Element root = document.getRootElement();
//4.获取根节点的namespace属性取值
String namespace = root.attributeValue("namespace");//是组成map中key的部分
//5.获取所有的select节点
List<Element> selectElements = root.selectNodes("//select");
//6.遍历select节点集合
for(Element selectElement : selectElements){
//取出id属性的值 组成map中key的部分
String id = selectElement.attributeValue("id");
//取出resultType属性的值 组成map中value的部分
String resultType = selectElement.attributeValue("resultType");
//取出文本内容 组成map中value的部分
String queryString = selectElement.getText();
//创建Key
String key = namespace+"."+id;
//创建Value
Mapper mapper = new Mapper();
mapper.setQueryString(queryString);
mapper.setResultType(resultType);
//把key和value存入mappers中
mappers.put(key,mapper);
}
return mappers;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
in.close();
}
}
/**
* 根据传入的参数,得到dao中所有被select注解标注的方法。
* 根据方法名称和类名,以及方法上注解value属性的值,组成Mapper的必要信息
* @param daoClassPath
* @return
*/
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();//List<User>
//判断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;
}
}