分析流程
创建 Maven 工程
Groupid:com.itheima
ArtifactId:mybatis02
Packing:jar
引入相关坐标
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
引入工具类到项目中
public class DataSourceUtil {
public static Connection getConnection(Configuration cfg){
try {
Class.forName(cfg.getDriver());
return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword());
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
public class Executor {
public <E> List<E> selectList(Mapper mapper, Connection conn) {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String queryString = mapper.getQueryString();
String resultType = mapper.getResultType();
Class domainClass = Class.forName(resultType);
pstm = conn.prepareStatement(queryString);
rs = pstm.executeQuery();
List<E> list = new ArrayList<E>();
while(rs.next()) {
E obj = (E)domainClass.newInstance();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
String columnName = rsmd.getColumnName(i);
Object columnValue = rs.getObject(columnName);
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();
}
}
}
}
public class XMLConfigBuilder {
public static Configuration loadConfiguration(InputStream config){
try{
Configuration cfg = new Configuration();
SAXReader reader = new SAXReader();
Document document = reader.read(config);
Element root = document.getRootElement();
List<Element> propertyElements = root.selectNodes("//property");
for(Element propertyElement : propertyElements){
String name = propertyElement.attributeValue("name");
if("driver".equals(name)){
String driver = propertyElement.attributeValue("value");
cfg.setDriver(driver);
}
if("url".equals(name)){
String url = propertyElement.attributeValue("value");
cfg.setUrl(url);
}
if("username".equals(name)){
String username = propertyElement.attributeValue("value");
cfg.setUsername(username);
}
if("password".equals(name)){
String password = propertyElement.attributeValue("value");
cfg.setPassword(password);
}
}
List<Element> mapperElements = root.selectNodes("//mappers/mapper");
for(Element mapperElement : mapperElements){
Attribute attribute = mapperElement.attribute("resource");
if(attribute != null){
System.out.println("使用的是XML");
String mapperPath = attribute.getValue();
Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath);
cfg.setMappers(mappers);
}else{
System.out.println("使用的是注解");
String daoClassPath = mapperElement.attributeValue("class");
Map<String,Mapper> mappers = loadMapperAnnotation(daoClassPath);
cfg.setMappers(mappers);
}
}
return cfg;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
try {
config.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException {
InputStream in = null;
try{
Map<String,Mapper> mappers = new HashMap<String,Mapper>();
in = Resources.getResourceAsStream(mapperPath);
SAXReader reader = new SAXReader();
Document document = reader.read(in);
Element root = document.getRootElement();
String namespace = root.attributeValue("namespace");
List<Element> selectElements = root.selectNodes("//select");
for(Element selectElement : selectElements){
String id = selectElement.attributeValue("id");
String resultType = selectElement.attributeValue("resultType");
String queryString = selectElement.getText();
String key = namespace+"."+id;
Mapper mapper = new Mapper();
mapper.setQueryString(queryString);
mapper.setResultType(resultType);
mappers.put(key,mapper);
}
return mappers;
}catch(Exception e){
throw new RuntimeException(e);
}finally{
in.close();
}
}
private static Map<String,Mapper> loadMapperAnnotation(String daoClassPath)throws Exception{
Map<String,Mapper> mappers = new HashMap<String, Mapper>();
Class daoClass = Class.forName(daoClassPath);
Method[] methods = daoClass.getMethods();
for(Method method : methods){
boolean isAnnotated = method.isAnnotationPresent(Select.class);
if(isAnnotated){
Mapper mapper = new Mapper();
Select selectAnno = method.getAnnotation(Select.class);
String queryString = selectAnno.value();
mapper.setQueryString(queryString);
Type type = method.getGenericReturnType();
if(type instanceof ParameterizedType){
ParameterizedType ptype = (ParameterizedType)type;
Type[] types = ptype.getActualTypeArguments();
Class domainClass = (Class)types[0];
String resultType = domainClass.getName();
mapper.setResultType(resultType);
}
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className+"."+methodName;
mappers.put(key,mapper);
}
}
return mappers;
}
}
引入自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select {
String value();
}
引入配置类
public class Configuration {
private String driver;
private String url;
private String username;
private String password;
private Map<String,Mapper> mappers = new HashMap<String,Mapper>();
public Map<String, Mapper> getMappers() {
return mappers;
}
public void setMappers(Map<String, Mapper> mappers) {
this.mappers.putAll(mappers);
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
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;
}
}
public class Mapper {
private String queryString;
private String resultType;
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
}
使用类加载器读取配置文件的类
public class Resources {
public static InputStream getResourceAsStream(String filePath){
return Resources.class.getClassLoader().getResourceAsStream(filePath);
}
}
引入SQL核心类
public interface SqlSession {
<T> T getMapper(Class<T> daoInterfaceClass);
void close();
}
public interface SqlSessionFactory {
SqlSession openSession();
}
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(InputStream config){
Configuration cfg = XMLConfigBuilder.loadConfiguration(config);
return new DefaultSqlSessionFactory(cfg);
}
}
public class DefaultSqlSession implements SqlSession {
private Configuration cfg;
private Connection connection;
public DefaultSqlSession(Configuration cfg){
this.cfg = cfg;
connection = DataSourceUtil.getConnection(cfg);
}
@Override
public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
new Class[]{daoInterfaceClass},new MapperProxy(cfg.getMappers(),connection));
}
@Override
public void close() {
if(connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class DefaultSqlSessionFactory implements SqlSessionFactory{
private Configuration cfg;
public DefaultSqlSessionFactory(Configuration cfg){
this.cfg = cfg;
}
@Override
public SqlSession openSession() {
return new DefaultSqlSession(cfg);
}
}
public class MapperProxy implements InvocationHandler {
private Map<String,Mapper> mappers;
private Connection conn;
public MapperProxy(Map<String,Mapper> mappers,Connection conn){
this.mappers = mappers;
this.conn = conn;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
String className = method.getDeclaringClass().getName();
String key = className+"."+methodName;
Mapper mapper = mappers.get(key);
if(mapper == null){
throw new IllegalArgumentException("传入的参数有误");
}
return new Executor().selectList(mapper,conn);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助。更多教程请访问码农之家
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~