Skip to content

Commit c56b34d

Browse files
author
Aa\aAa
committed
实现xml方式 查询方式
0 parents  commit c56b34d

18 files changed

+469
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
target

MoodBatis.iml

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
3+
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
4+
<output url="file://$MODULE_DIR$/target/classes" />
5+
<output-test url="file://$MODULE_DIR$/target/test-classes" />
6+
<content url="file://$MODULE_DIR$">
7+
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
8+
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
9+
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
10+
<excludeFolder url="file://$MODULE_DIR$/target" />
11+
</content>
12+
<orderEntry type="inheritedJdk" />
13+
<orderEntry type="sourceFolder" forTests="false" />
14+
<orderEntry type="library" name="Maven: dom4j:dom4j:1.6.1" level="project" />
15+
<orderEntry type="library" name="Maven: xml-apis:xml-apis:1.0.b2" level="project" />
16+
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.44" level="project" />
17+
<orderEntry type="library" name="Maven: org.projectlombok:lombok:1.18.4" level="project" />
18+
</component>
19+
</module>

pom.xml

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>MoodBatis</groupId>
8+
<artifactId>MoodBatis</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<dependencies>
12+
<dependency>
13+
<groupId>dom4j</groupId>
14+
<artifactId>dom4j</artifactId>
15+
<version>1.6.1</version>
16+
</dependency>
17+
<!-- MySQL -->
18+
<dependency>
19+
<groupId>mysql</groupId>
20+
<artifactId>mysql-connector-java</artifactId>
21+
<version>5.1.44</version>
22+
</dependency>
23+
<dependency>
24+
<groupId>org.projectlombok</groupId>
25+
<artifactId>lombok</artifactId>
26+
<version>1.18.4</version>
27+
28+
</dependency>
29+
30+
</dependencies>
31+
32+
</project>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.mood.SqlSession;
2+
3+
import com.mood.config.Function;
4+
5+
public interface Excutor {
6+
public <T> T query(Function statement, Object parameter);
7+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.mood.SqlSession;
2+
3+
import com.mood.bean.User;
4+
import com.mood.config.Function;
5+
import com.mood.config.MapperBean;
6+
7+
import java.sql.Connection;
8+
import java.sql.PreparedStatement;
9+
import java.sql.ResultSet;
10+
import java.sql.SQLException;
11+
12+
public class MoodExcutor implements Excutor {
13+
private MoodSqlSessionFactory xmlConfiguration = new MoodSqlSessionFactory();
14+
15+
@Override
16+
public <T> T query(Function sql, Object parameter) {
17+
StatementHandler handler = new StatementHandler(xmlConfiguration);
18+
return handler.query(sql, parameter);
19+
}
20+
21+
22+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.mood.SqlSession;
2+
3+
import com.mood.config.Function;
4+
import com.mood.config.MapperBean;
5+
6+
import java.lang.reflect.InvocationHandler;
7+
import java.lang.reflect.Method;
8+
import java.util.List;
9+
10+
public class MoodMapperProxy implements InvocationHandler {
11+
private MoodSession session;
12+
private MoodSqlSessionFactory sessionFactory;
13+
14+
public MoodMapperProxy(MoodSqlSessionFactory sessionFactory, MoodSession session) {
15+
this.session = session;
16+
this.sessionFactory = sessionFactory;
17+
}
18+
19+
@Override
20+
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
21+
MapperBean readMapper = sessionFactory.getXMLMapperBean("UserMapper.xml");
22+
//是否是xml文件对应的接口
23+
if(!method.getDeclaringClass().getName().equals(readMapper.getInterfaceName())){
24+
return null;
25+
}
26+
List<Function> list = readMapper.getList();
27+
if(list != null && list.size() > 0){
28+
for (Function function : list) {
29+
//id是否和接口方法名一样
30+
if(method.getName().equals(function.getFuncName())){
31+
return session.selectOne(function, String.valueOf(args[0]));
32+
}
33+
}
34+
}
35+
return null;
36+
}
37+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.mood.SqlSession;
2+
3+
import com.mood.config.Function;
4+
import com.mood.config.MapperBean;
5+
6+
import java.lang.reflect.Proxy;
7+
import java.util.HashMap;
8+
import java.util.Map;
9+
10+
public class MoodSession {
11+
private Excutor excutor = new MoodExcutor();
12+
13+
static private MoodSqlSessionFactory myConfiguration = new MoodSqlSessionFactory();
14+
15+
16+
public <T> T selectOne(Function statement, Object parameter) {
17+
return excutor.query(statement, parameter);
18+
}
19+
20+
public <T> T getMapper(Class cla) {
21+
return (T) Proxy.newProxyInstance(cla.getClassLoader(), new Class[]{cla}, new MoodMapperProxy(myConfiguration, this));
22+
}
23+
}
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
package com.mood.SqlSession;
2+
3+
import com.mood.config.Function;
4+
import com.mood.config.MapperBean;
5+
import org.dom4j.Document;
6+
import org.dom4j.DocumentException;
7+
import org.dom4j.Element;
8+
import org.dom4j.io.SAXReader;
9+
10+
import java.io.InputStream;
11+
import java.sql.Connection;
12+
import java.sql.DriverManager;
13+
import java.sql.SQLException;
14+
import java.util.ArrayList;
15+
import java.util.Iterator;
16+
import java.util.List;
17+
18+
public class MoodSqlSessionFactory {
19+
20+
//加载
21+
private static final ClassLoader classLoader = ClassLoader.getSystemClassLoader();
22+
23+
//初始化
24+
public Connection bulider(String path) {
25+
try {
26+
InputStream stream = classLoader.getResourceAsStream(path);
27+
28+
SAXReader reader = new SAXReader();
29+
Document document = reader.read(stream);
30+
Element root = document.getRootElement();
31+
return evalDataSource(root);
32+
} catch (DocumentException e) {
33+
throw new RuntimeException("error occured while evaling xml " + path);
34+
}
35+
36+
}
37+
38+
private Connection evalDataSource(Element node) {
39+
if (!"database".equals(node.getName())) {
40+
throw new RuntimeException("root should be <database>");
41+
}
42+
String driverClassName = null;
43+
String url = null;
44+
String username = null;
45+
String password = null;
46+
//获取属性节点
47+
for (Object item : node.elements("property")) {
48+
Element i = (Element) item;
49+
String value = getValue(i);
50+
String name = i.attributeValue("name");
51+
if (name == null || value == null) {
52+
throw new RuntimeException("[database]: <property> should contain name and value");
53+
}
54+
//赋值
55+
switch (name) {
56+
case "url":
57+
url = value;
58+
break;
59+
case "username":
60+
username = value;
61+
break;
62+
case "password":
63+
password = value;
64+
break;
65+
case "driverClassName":
66+
driverClassName = value;
67+
break;
68+
default:
69+
throw new RuntimeException("[database]: <property> unknown name");
70+
}
71+
}
72+
73+
Connection connection = null;
74+
try {
75+
Class.forName(driverClassName);
76+
//建立数据库链接
77+
connection = DriverManager.getConnection(url, username, password);
78+
} catch (ClassNotFoundException e) {
79+
e.printStackTrace();
80+
} catch (SQLException e) {
81+
e.printStackTrace();
82+
}
83+
return connection;
84+
}
85+
86+
//获取property属性的值,如果有value值,则读取 没有设置value,则读取内容
87+
private String getValue(Element node) {
88+
return node.hasContent() ? node.getText() : node.attributeValue("value");
89+
}
90+
91+
public MapperBean getXMLMapperBean(String path) {
92+
MapperBean bean = new MapperBean();
93+
InputStream resourceAsStream = classLoader.getResourceAsStream(path);
94+
SAXReader saxReader = new SAXReader();
95+
Document document = null;
96+
try {
97+
document = saxReader.read(resourceAsStream);
98+
Element rootElement = document.getRootElement();
99+
bean.setInterfaceName(rootElement.attributeValue("nameSpace").trim());
100+
List<Function> list = new ArrayList<Function>(); //用来存储方法的List
101+
for(Iterator rootIter = rootElement.elementIterator(); rootIter.hasNext();) {//遍历根节点下所有子节点
102+
Function fun = new Function(); //用来存储一条方法的信息
103+
Element e = (Element) rootIter.next();
104+
String sqltype = e.getName().trim();
105+
String funcName = e.attributeValue("id").trim();
106+
String sql = e.getText().trim();
107+
String resultType = e.attributeValue("resultType").trim();
108+
fun.setSqltype(sqltype);
109+
fun.setFuncName(funcName);
110+
Object newInstance=null;
111+
try {
112+
newInstance = Class.forName(resultType).newInstance();
113+
} catch (InstantiationException e1) {
114+
e1.printStackTrace();
115+
} catch (IllegalAccessException e1) {
116+
e1.printStackTrace();
117+
} catch (ClassNotFoundException e1) {
118+
e1.printStackTrace();
119+
}
120+
fun.setResultType(newInstance);
121+
fun.setSql(sql);
122+
list.add(fun);
123+
}
124+
bean.setList(list);
125+
} catch (DocumentException e) {
126+
e.printStackTrace();
127+
}
128+
129+
130+
return bean;
131+
}
132+
133+
public static void main(String[] args) {
134+
MoodSqlSessionFactory myConfiguration = new MoodSqlSessionFactory();
135+
// Connection con = myConfiguration.bulider("config.xml");
136+
MapperBean xmlMapperBean = myConfiguration.getXMLMapperBean("UserMapper.xml");
137+
System.out.println(xmlMapperBean);
138+
}
139+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.mood.SqlSession;
2+
3+
import java.lang.reflect.Field;
4+
import java.lang.reflect.Method;
5+
import java.sql.ResultSet;
6+
import java.sql.SQLException;
7+
8+
public class ResultSetHandler {
9+
//解析结果。生成实体
10+
public <T> T handler(ResultSet resultSet, Object obj) {
11+
12+
//
13+
Class clazz = obj.getClass();
14+
// Object obj = null;
15+
try {
16+
if (resultSet.next()){
17+
int i = 0;
18+
for (Field field: clazz.getDeclaredFields()){
19+
setValue(obj,field,resultSet,i);
20+
}
21+
22+
}
23+
24+
} catch (Exception e) {
25+
e.printStackTrace();
26+
}
27+
28+
return (T)obj;
29+
30+
31+
}
32+
33+
private void setValue(Object obj, Field field, ResultSet resultSet, int i) throws Exception {
34+
35+
Method m = obj.getClass().getMethod("set"+upperCapital(field.getName()),field.getType());
36+
37+
m.invoke(obj,getResult(field,resultSet));
38+
39+
}
40+
41+
private Object getResult(Field field, ResultSet rs) throws SQLException {
42+
//bean属性的名字必须要和数据库column的名字一样
43+
Class<?> type = field.getType();
44+
if("int".equals(type.getName()) ||Integer.class == type ){
45+
return rs.getInt(field.getName());
46+
}
47+
if(String.class == type){
48+
return rs.getString(field.getName());
49+
}
50+
return rs.getString(field.getName());
51+
52+
53+
54+
}
55+
56+
private String upperCapital(String name) {
57+
58+
char[] nameAry = name.toCharArray();
59+
nameAry[0] -= 32;
60+
return new String(nameAry);
61+
}
62+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.mood.SqlSession;
2+
3+
import com.mood.config.Function;
4+
5+
import java.sql.Connection;
6+
import java.sql.PreparedStatement;
7+
import java.sql.SQLException;
8+
9+
public class StatementHandler {
10+
private MoodSqlSessionFactory sqlSessionFactory;
11+
private ResultSetHandler resultSetHandler = new ResultSetHandler();
12+
13+
public StatementHandler(MoodSqlSessionFactory sqlSessionFactory) {
14+
this.sqlSessionFactory = sqlSessionFactory;
15+
}
16+
17+
public <T> T query(Function function, Object parameter) {
18+
Connection conn = this.getConnection();
19+
try {
20+
String format = String.format(function.getSql(),
21+
Integer.parseInt(String.valueOf(parameter)));
22+
PreparedStatement p = conn.prepareStatement(
23+
format
24+
);
25+
p.setObject(1, parameter);
26+
p.execute();
27+
return resultSetHandler.handler(p.getResultSet(), function.getResultType());
28+
} catch (SQLException e) {
29+
e.printStackTrace();
30+
}
31+
return null;
32+
}
33+
34+
private Connection getConnection() {
35+
try {
36+
Connection connection = sqlSessionFactory.bulider("config.xml");
37+
return connection;
38+
} catch (Exception e) {
39+
e.printStackTrace();
40+
}
41+
return null;
42+
}
43+
}

0 commit comments

Comments
 (0)