MyBatis学习(三)

简单手写MyBatis框架

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.xiaoguan.godbatis;

/**
* 框架的常用类
*/
public class Const {
private Const() {
}

public static final String UN_POOLED_DATASOURCE="UNPOOLED";
public static final String POOLED_DATASOURCE="POOLED";
public static final String JNDI_DATASOURCE="JNDI";
public static final String JDBC_TRANSACTION="JDBC";
public static final String MANAGED_TRANSACTION="MANAGED";
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.xiaoguan.godbatis;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
* JDBC事务管理器
*/
public class JDBCTransaction implements Transaction{
private DataSource dataSource;
private boolean autoCommit;
private Connection connection;
@Override
public Connection getConnection() {
return connection;
}

public JDBCTransaction(DataSource dataSource, boolean autoCommit) {
this.dataSource = dataSource;
this.autoCommit = autoCommit;
}

@Override
public void commit() {
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}

}

@Override
public void rollback() {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}

@Override
public void close() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void openConnection(){
if (connection == null) {
try {
connection = dataSource.getConnection();
connection.setAutoCommit(autoCommit);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.xiaoguan.godbatis;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class JNDIDataSource implements javax.sql.DataSource{
@Override
public Connection getConnection() throws SQLException {
return null;
}

@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}

@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}

@Override
public void setLogWriter(PrintWriter out) throws SQLException {

}

@Override
public void setLoginTimeout(int seconds) throws SQLException {

}

@Override
public int getLoginTimeout() throws SQLException {
return 0;
}

@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}

@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}

@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.xiaoguan.godbatis;

import java.sql.Connection;

/**
* Managed事务管理器
*/
public class ManagedTransaction implements Transaction{
@Override
public void commit() {

}

@Override
public void rollback() {

}

@Override
public void close() {

}

@Override
public void openConnection() {

}

@Override
public Connection getConnection() {
return null;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.xiaoguan.godbatis;

import java.util.Objects;

/**
* 封装了一个sql标签
*/
public class MappedStatement {
private String sql;
/**
* 要封装的结果集类型
*/
private String resultType;

public MappedStatement() {
}

public MappedStatement(String sql, String resultType) {
this.sql = sql;
this.resultType = resultType;
}

public String getSql() {
return sql;
}

public void setSql(String sql) {
this.sql = sql;
}

@Override
public String toString() {
return "MappedStatement{" +
"sql='" + sql + '\'' +
", resultType='" + resultType + '\'' +
'}';
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MappedStatement that = (MappedStatement) o;
return Objects.equals(getSql(), that.getSql()) && Objects.equals(getResultType(), that.getResultType());
}

@Override
public int hashCode() {
return Objects.hash(getSql(), getResultType());
}

public String getResultType() {
return resultType;
}

public void setResultType(String resultType) {
this.resultType = resultType;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.xiaoguan.godbatis;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
* POOLED
* 从数据库连接池获取Connection连接池对象
*/
public class PooledDataSource implements javax.sql.DataSource{
@Override
public Connection getConnection() throws SQLException {
return null;
}

@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}

@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}

@Override
public void setLogWriter(PrintWriter out) throws SQLException {

}

@Override
public void setLoginTimeout(int seconds) throws SQLException {

}

@Override
public int getLoginTimeout() throws SQLException {
return 0;
}

@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}

@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}

@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package com.xiaoguan.godbatis;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;

/**
* 专门负责执行sql语句的会话对象
*/
public class SqlSession {
private SqlSessionFactory sqlSessionFactory;

public SqlSession(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}

public int insert(String sqlId,Object pojo){
int count=0;
Connection connection=null;
PreparedStatement ps=null;
try {
connection=sqlSessionFactory.getTransaction().getConnection();
String godSql=sqlSessionFactory.getSqlMap().get(sqlId).getSql();
String sql=godSql.replaceAll("#\\{[0-9a-zA-Z_$]*}","?");
ps = connection.prepareStatement(sql);
int fromIndex=0;
int index=0;
while (true){
int jingIndex=godSql.indexOf("#",fromIndex);
if (jingIndex<0) {
break;
}
index++;
int youKuoHaoIndex=godSql.indexOf("}",fromIndex);
String prepareName = godSql.substring(jingIndex + 2, youKuoHaoIndex).trim();
String getMethodName="get"+prepareName.toUpperCase().charAt(0)+prepareName.substring(1);
Method getMethod = pojo.getClass().getDeclaredMethod(getMethodName);
Object propertyValue = getMethod.invoke(pojo);
ps.setString(index,propertyValue.toString());
fromIndex=youKuoHaoIndex+1;
}
count = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

return count;
}

// public static void main(String[] args) {
// String sql="insert into dept values(#{deptno},#{dname},#{loc})";
// int fromIndex=0;
// int index=0;
// while (true){
// int jingIndex=sql.indexOf("#",fromIndex);
// if (jingIndex<0) {
// break;
// }
// index++;
// System.out.println(index);
// int youKuoHaoIndex=sql.indexOf("}",fromIndex);
// String prepareName = sql.substring(jingIndex + 2, youKuoHaoIndex).trim();
// System.out.println(prepareName);
// fromIndex=youKuoHaoIndex+1;
// }
// }
public Object selectOne(String sqlId,Object param){
Object obj=null;
Connection connection=sqlSessionFactory.getTransaction().getConnection();
PreparedStatement ps=null;
ResultSet rs=null;
try {
MappedStatement mappedStatement = sqlSessionFactory.getSqlMap().get(sqlId);
String godsql = mappedStatement.getSql();
String resultType = mappedStatement.getResultType();
String sql=godsql.replaceAll("#\\{[0-9a-zA-Z_$]*}","?");
ps = connection.prepareStatement(sql);
ps.setString(1,param.toString());
rs = ps.executeQuery();
if(rs.next()){
Class resultTypeClass = Class.forName(resultType);
obj = resultTypeClass.newInstance();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
for (int i = 0; i < columnCount; i++) {
String propertyName = metaData.getColumnName(i+1);
String setMethodName="set"+propertyName.toUpperCase().charAt(0)+propertyName.substring(1);
Method setMethod = resultTypeClass.getDeclaredMethod(setMethodName,String.class);
setMethod.invoke(obj,rs.getString(propertyName));
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return obj;
}
public void commit(){
sqlSessionFactory.getTransaction().commit();
}

public void rollback(){
sqlSessionFactory.getTransaction().rollback();
}

public void close(){
sqlSessionFactory.getTransaction().close();
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.xiaoguan.godbatis;

import java.sql.Connection;
import java.util.Map;

public class SqlSessionFactory {
/**
* 事务管理器属性
*/
private Transaction transaction;
private Map<String,MappedStatement> sqlMap;
public SqlSessionFactory(Transaction transaction, Map<String, MappedStatement> sqlMap) {
this.transaction = transaction;
this.sqlMap = sqlMap;
}

public SqlSessionFactory() {
}

public Transaction getTransaction() {
return transaction;
}

public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}

public Map<String, MappedStatement> getSqlMap() {
return sqlMap;
}

public void setSqlMap(Map<String, MappedStatement> sqlMap) {
this.sqlMap = sqlMap;
}

/**
* 获取sql会话对象
* @return sqlSession
*/
public SqlSession openSession(){
transaction.openConnection();
SqlSession sqlSession = new SqlSession(this);
return sqlSession;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.xiaoguan.godbatis;

import com.xiaoguan.utils.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 构建器对象
*/
public class SqlSessionFactoryBuilder {
public SqlSessionFactoryBuilder() {
}

/**
* 返回指向godbatis-config.xml的SqlSessionFactory对象
* @param in
* @return SqlSessionFactory
*/
public SqlSessionFactory build(InputStream in){
SqlSessionFactory sqlSessionFactory=null;
try {
SAXReader reader=new SAXReader();
Document document = reader.read(in);
Element environments = (Element) document.selectSingleNode("/configuration/environments");
String environmentsDefault = environments.attributeValue("default");
Element environment = (Element) document.selectSingleNode("/configuration/environments/environment[@id='" + environmentsDefault + "']");
//获取事务管理器节点
Element transactionManager = environment.element("transactionManager");
Element dataSourceElt = environment.element("dataSource");
List<String> sqlMapperXMLPath= new ArrayList<>();
List<Node> nodes = document.selectNodes("//mapper");
nodes.forEach(node -> {
Element mapperElts = (Element) node;
String resource = mapperElts.attributeValue("resource");
sqlMapperXMLPath.add(resource);
});
DataSource dataSource=getDataSource(dataSourceElt);
Transaction transaction=getTransaction(dataSource,transactionManager);
Map<String, MappedStatement> sqlMap=getMappedStatements(sqlMapperXMLPath);
sqlSessionFactory = new SqlSessionFactory(transaction,sqlMap);
} catch (DocumentException e) {
e.printStackTrace();
}
return sqlSessionFactory;

}

private Map<String, MappedStatement> getMappedStatements(List<String> sqlMapperXMLPath) {
Map<String, MappedStatement> stringMappedStatementMap =new HashMap<>();
sqlMapperXMLPath.forEach(sqlFile->{
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(Resources.getResourceAsStream(sqlFile));
Element mapperElements = (Element) document.selectSingleNode("mapper");
String namespace = mapperElements.attributeValue("namespace");
List<Element> mapperChildElements = mapperElements.elements();
mapperChildElements.forEach(element -> {
String id = element.attributeValue("id");
String sqlId=namespace+"."+id;
String resultType = element.attributeValue("resultType");
String sql = element.getTextTrim();
MappedStatement mappedStatement = new MappedStatement(sql, resultType);
stringMappedStatementMap.put(sqlId,mappedStatement);
});
} catch (DocumentException e) {
e.printStackTrace();
}
});
return stringMappedStatementMap;
}

private Transaction getTransaction(DataSource dataSource, Element transactionManager) {
Transaction transaction=null;
String JDBCType = transactionManager.attributeValue("type").trim().toUpperCase();
if (Const.JDBC_TRANSACTION.equals(JDBCType)) {
transaction =new JDBCTransaction(dataSource,false);
}
if (Const.MANAGED_TRANSACTION.equals(JDBCType)) {
transaction=new ManagedTransaction();
}
return transaction;

}

private DataSource getDataSource(Element dataSourceElt) {
Map<String,String> map=new HashMap<>();
String dataSourceType = dataSourceElt.attributeValue("type").trim().toUpperCase();
List<Element> propertyElts = dataSourceElt.elements("property");
propertyElts.forEach(propertyElt ->{
String name = propertyElt.attributeValue("name");
String value = propertyElt.attributeValue("value");
map.put(name,value);
});
DataSource dataSource=null;
if (Const.UN_POOLED_DATASOURCE.equals(dataSourceType)) {
dataSource=new UnPooledDataSource(map.get("driver"),map.get("url"),map.get("username"),map.get("password"));
}
if (Const.POOLED_DATASOURCE.equals(dataSourceType)) {
dataSource=new PooledDataSource();
}
if (Const.JNDI_DATASOURCE.equals(dataSourceType)) {
dataSource=new JNDIDataSource();
}
return dataSource;


}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.xiaoguan.godbatis;

import java.sql.Connection;

/**
* 事务管理接口
*/
public interface Transaction {
/**
* 提交事务,管理事务,关闭事务
*/
void commit();
void rollback();
void close();
void openConnection();
Connection getConnection();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.xiaoguan.godbatis;


import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
* 数据源的实现类UNPPPLED
* 不使用数据库连接池,每一次都新建对象
*/
public class UnPooledDataSource implements javax.sql.DataSource {
private String url;
private String username;
private String password;

public UnPooledDataSource(String driver, String url, String username, String password) {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
this.url = url;
this.username = username;
this.password = password;
}

@Override
public Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}

@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}

@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}

@Override
public void setLogWriter(PrintWriter out) throws SQLException {

}

@Override
public void setLoginTimeout(int seconds) throws SQLException {

}

@Override
public int getLoginTimeout() throws SQLException {
return 0;
}

@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}

@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}

@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.xiaoguan.pojo;

import java.util.Objects;

/**
* 封装汽车相关信息的普通java类
*/
public class Car {
//建议使用包装类
private Long id;
private String carNum;
private String brand;
private Double guidePrice;
private String produceTime;
private String carType;

public Car() {
}

public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {
this.id = id;
this.carNum = carNum;
this.brand = brand;
this.guidePrice = guidePrice;
this.produceTime = produceTime;
this.carType = carType;
}

@Override
public String toString() {
return "Car{" +
"id=" + id +
", carNum='" + carNum + '\'' +
", brand='" + brand + '\'' +
", guidePrice=" + guidePrice +
", produceTime='" + produceTime + '\'' +
", carType='" + carType + '\'' +
'}';
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return Objects.equals(getId(), car.getId()) && Objects.equals(getCarNum(), car.getCarNum()) && Objects.equals(getBrand(), car.getBrand()) && Objects.equals(getGuidePrice(), car.getGuidePrice()) && Objects.equals(getProduceTime(), car.getProduceTime()) && Objects.equals(getCarType(), car.getCarType());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getCarNum(), getBrand(), getGuidePrice(), getProduceTime(), getCarType());
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getCarNum() {
return carNum;
}

public void setCarNum(String carNum) {
this.carNum = carNum;
}

public String getBrand() {
return brand;
}

public void setBrand(String brand) {
this.brand = brand;
}

public Double getGuidePrice() {
return guidePrice;
}

public void setGuidePrice(Double guidePrice) {
this.guidePrice = guidePrice;
}

public String getProduceTime() {
return produceTime;
}

public void setProduceTime(String produceTime) {
this.produceTime = produceTime;
}

public String getCarType() {
return carType;
}

public void setCarType(String carType) {
this.carType = carType;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.xiaoguan.utils;

import java.io.InputStream;

/**
* 专门完成类路径的加载
*/
public class Resources {
private Resources() {
}

/**
* 从类路径加载资源
* @param resource
* @return InputStream
*/
public static InputStream getResourceAsStream(String resource){
return ClassLoader.getSystemClassLoader().getResourceAsStream(resource);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.xiaoguan.pojo;

import java.util.Objects;

public class User {
private String id;
private String name;
private String age;

@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(getId(), user.getId()) && Objects.equals(getName(), user.getName()) && Objects.equals(getAge(), user.getAge());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getName(), getAge());
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

public User(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}

public User() {
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.xiaoguan.test;

import com.xiaoguan.godbatis.SqlSession;
import com.xiaoguan.godbatis.SqlSessionFactory;
import com.xiaoguan.godbatis.SqlSessionFactoryBuilder;
import com.xiaoguan.pojo.User;
import com.xiaoguan.utils.Resources;
import org.junit.Test;

public class GodBatisTest {
@Test
public void testSelectOne(){
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
Object obj = sqlSession.selectOne("xiaoguan.selectById", "224");
System.out.println(obj);
// sqlSession.commit();
sqlSession.close();
}
@Test
public void testInsertUser(){
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User("222", "xiaoguan", "22");
int count = sqlSession.insert("xiaoguan.insertUser", user);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testSqlSessionFactory(){
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory build = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
System.out.println(build);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.xiaoguan.test;

import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class ParseXMLByDom4jTest {
@Test
public void testParseSqlMapperXML() throws DocumentException {
SAXReader saxReader = new SAXReader();
Document carMapper = saxReader.read(ClassLoader.getSystemClassLoader().getResourceAsStream("CarMapper.xml"));
String xpath="/mapper";
Element mapper =(Element) carMapper.selectSingleNode(xpath);
String namespace = mapper.attributeValue("namespace");
System.out.println(namespace);
List<Element> elements = mapper.elements();
elements.forEach(element -> {
String id = element.attributeValue("id");
System.out.println(id);
//获取resultType
String resultType = element.attributeValue("resultType");
System.out.println(resultType);
//获取标签中的sql语句
String text = element.getTextTrim();
System.out.println(text);
String sql = text.replaceAll("#\\{[0-9A-Za-z_$]*}", "?");
System.out.println(sql);
});


}
@Test
public void testParseMybatisConfigXML() throws DocumentException {
SAXReader saxReader = new SAXReader();
InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("mybatis-config.xml");
Document document = saxReader.read(resourceAsStream);
// Element rootElement = document.getRootElement();
// String rootElementName = rootElement.getName();
// System.out.println(rootElementName);//获取根节点
String xpath="/configuration/environments";
Element environments =(Element) document.selectSingleNode(xpath);
String defaultValue = environments.attributeValue("default");
xpath="/configuration/environments/environment[@id='"+defaultValue+"']";
Element environment = (Element) document.selectSingleNode(xpath);
Element transactionManager = environment.element("transactionManager");//element用来获取孩子节点
String transactionType = transactionManager.attributeValue("type");
// System.out.println("事务管理器类型:"+transactionType);
Element dataSource = environment.element("dataSource");
String dataSourceType = dataSource.attributeValue("type");
// System.out.println("数据源类型"+dataSourceType);
List<Element> properties = dataSource.elements("property");

properties.forEach(propertyElement ->{
String name = propertyElement.attributeValue("name");
String value = propertyElement.attributeValue("value");
System.out.println(name+"="+value);
});
//获取所有的map标签
xpath="//mappers";//不想从根开始写可以用//来代替
Element mappers =(Element) document.selectSingleNode(xpath);
List<Element> mapper = mappers.elements("mapper");
mapper.forEach(mapperValue -> {
String resourceValue = mapperValue.attributeValue("resource");
System.out.println(resourceValue);
});

}
}

框架的测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.xiaoguan.pojo;

import java.util.Objects;

public class User {
private String id;
private String name;
private String age;

public User() {
}

public User(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(getId(), user.getId()) && Objects.equals(getName(), user.getName()) && Objects.equals(getAge(), user.getAge());
}

@Override
public int hashCode() {
return Objects.hash(getId(), getName(), getAge());
}

@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="68963120g"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xiaoguan">
<insert id="testgabatis" >
insert into t_user values(#{id},#{name},#{age});
</insert>
<select id="select" resultType="com.xiaoguan.pojo.User">
select * from t_user where id=#{id};
</select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.xiaoguan.test;

import com.xiaoguan.godbatis.SqlSession;
import com.xiaoguan.godbatis.SqlSessionFactory;
import com.xiaoguan.godbatis.SqlSessionFactoryBuilder;
import com.xiaoguan.pojo.User;
import com.xiaoguan.utils.Resources;
import org.junit.Test;

public class UserMapperTest {
@Test
public void testInsert(){
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("godbatis.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User("1234567", "xiaoguan", "23");
int count = sqlSession.insert("xiaoguan.testgabatis", user);
System.out.println(count);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testSelect(){
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("godbatis.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
Object objUser = sqlSession.selectOne("xiaoguan.select", 1234567);
System.out.println(objUser);
sqlSession.close();
}
}