文章目錄
一、項目結構圖總覽
二、前期開發準備
2.1創建Maven工程
點擊finish即可
2.2pom.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>com.thinkcoder</groupId>
<artifactId>selfmybatis</artifactId>
<version>1.0.0</version>
<!--打包方式jar包-->
<packaging>jar</packaging>
<!--mysql驅動-->
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 操作日誌-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j</artifactId>
<version>2.12.1</version>
</dependency>
<!--解析xml文件-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
</project>
2.3建立數據庫操作的配置文件
建表的sql腳本
CREATE TABLE `user` (
`name` char(4) DEFAULT NULL,
`pwd` varchar(255) DEFAULT NULL,
`id` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
User類:屬性與數據庫表字段名稱保持一致
- 利用了ORM思想:Object Relational Mapping對象關係映射,把實體類的屬性和數據庫表對應起來,操作實體類就實現操作數據庫表
public class User {
private Integer id;
private String name;
private String pwd;
//getter和setter方法
public Integer getId() {return id;}
public void setId(Integer id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getPwd() {return pwd;}
public void setPwd(String pwd) {this.pwd = pwd;}
//重寫toString方法
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
IUserDao接口:操作數據庫的接口
public interface IUserDao {
//查詢所有操作
List<User> findAll();
}
SqlMapConfig.xml文件:配置連接數據庫信息及指定映射配置文件位置
<?xml version="1.0" encoding="UTF-8"?>
<!--mybatis的主配置文件-->
<configuration>
<!--配置環境-->
<environments default="mysql">
<!--配置mysql的環境-->
<environment id="mysql">
<!--配置事務的類型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置數據源(連接池)-->
<dataSource type="POOLED">
<!--配置連接數據庫的4個基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/selfproj"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的位置,映射配置文件指的是每個dao獨立的配置文件-->
<mappers>
<mapper resource="com/thinkcoder/dao/IUserDao.xml"/>
</mappers>
</configuration>
IUserDao.xml文件:配置方法映射的sql語句及返回結果類型
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="com.thinkcoder.dao.IUserDao">
<!--配置查詢所有記錄--><!--id爲方法的名稱-->
<select id="findAll" resultType="com.thinkcoder.domain.User">
select * from user
</select>
</mapper>
三、自定義MaBatis框架主要類總覽
爲了搞清主要類之間的調用關係,畫了一個時序圖,UML可是架構師的利器,要善於使用
上面的圖是重點:下面按照上圖調用關係用代碼實現
四、自定義MyBatis框架實現
測試類(client)
public class MybatisTest {
public static void main(String[] args) throws IOException {
//1.讀取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.創建SqlSessionFactory工廠
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工廠生產SqlSession對象
SqlSession session = factory.openSession();
//4.使用SqlSession創建Dao接口的代理對象,因爲IUserDao接口沒有實現類
IUserDao userDao = session.getMapper(IUserDao.class);
//5.使用代理對象執行方法
List<User> users = userDao.findAll();
for (User user:users){
System.out.println(user);
}
//6.釋放資源
session.close();
in.close();
}
}
Resources類
- 讀取配置文件
public class Resources {
/**
* @Description:根據傳入的參數,獲取一個字節輸入流
* @Author: Think-Coder
* @Param :filePath
*
* 在實際開發中讀取配置文件
* 1.使用類加載器,但是有要求:a文件不能過大,b文件必須在類路徑下(classpath)
* 2.使用ServletContext的getRealPath()
**/
public static InputStream getResourceAsStream(String filePath){
return Resources.class.getClassLoader().getResourceAsStream(filePath);
}
}
SqlSessionFactoryBuilder
- 構建者模式創建SqlSessionFactroy工廠
public class SqlSessionFactoryBuilder {
/**
* @Description:根據參數的字節輸入流來構建一個SqlSessionFactory工廠
* @Author: Think-Coder
* @Param :config
**/
public SqlSessionFactory build(InputStream config) {
//解析流需要解析xml工具類
Configuration conf = XMLConfigBuilder.loadConfiguration(config);
return new DefaultSqlSessionFactory(conf);
}
}
XMLConfigBuilder類
- dom4j+xpath技術解析XML文件
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/thinkcoder/dao/IUserDao.xml"
//把映射配置文件的內容獲取出來,封裝成一個map
Map<String, Mapper> mappers = loadMapperConfiguration(mapperPath);
//給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();
}
}
}
SqlSessionFactory接口:
public interface SqlSessionFactory {
/**
* @Description:用於打開一個新的SqlSession對象
**/
SqlSession openSession();
}
DefaultSqlSessionFactory類
- 實現SqlSessionFactory接口,生成sqlsession對象
/**
* @ClassName DefaultSqlSessionFactory
* @Author Think-Coder
* SqlSessionFactory接口的實現類
*/
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration conf;
public DefaultSqlSessionFactory(Configuration conf){
this.conf = conf;
}
/**
* @Description:用於創建一個新的操作數據庫對象
* @Return :SqlSession
**/
public SqlSession openSession() {
return new DefaultSqlSession((conf));
}
}
SqlSession接口
- 和數據庫交互的核心類
/**
* 自定義Mybatis中和數據庫交互的核心類
* 裏面可以創建dao接口的代理對象
* @Author Think-Coder
*/
public interface SqlSession {
/**
* @Description:根據參數創建一個代理對象
* @Param :daoInterfaceClass dao的接口字節碼
**/
<T> T getMapper(Class<T> daoInterfaceClass);
/**
* 釋放資源
*/
void close();
}
DefaultSqlSession類
- 實現SqlSession接口
/**
* @ClassName DefaultSqlSession
* @Author Think-Coder
* SqlSession接口的實現類
*/
public class DefaultSqlSession implements SqlSession {
private Configuration conf;
private Connection connection;
public DefaultSqlSession(Configuration conf){
this.conf = conf;
connection = DataSourceUtil.getConnection(conf);
}
/**
* @Description:用於創建代理對象
* @Param :daoInterfaceClass dao的接口字節碼
**/
public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T)Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
new Class[]{daoInterfaceClass},new MapperProxy(conf.getMappers(),connection));
}
/**
* @Description:釋放資源
**/
public void close() {
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
DataSourceUtil工具類
- 用於創建數據源
//用於創建數據源的工具類
public class DataSourceUtil {
//用於獲取一個連接
public static Connection getConnection(Configuration conf){
try{
Class.forName(conf.getDriver());
return DriverManager.getConnection(conf.getUrl(),conf.getUsername(),conf.getPassword());
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
MapperProxy類
- 用於增強原對象IUserDao接口,增強方法爲selectList方法
public class MapperProxy implements InvocationHandler {
//map的key是全限定類名+方法名
private Map<String, Mapper> mappers;
private Connection conn;
public MapperProxy(Map<String,Mapper> mappers,Connection conn){
this.mappers = mappers;
this.conn = conn;
}
//用於對方法的增強,我們的增強其實就是調用selectList方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//1.獲取方法名
String methodName = method.getName();
//2.獲取方法所在類的名稱
String className = method.getDeclaringClass().getName();
//3.組合key
String key = className+"."+methodName;
//4.獲取mappers中的Mapper對象
Mapper mapper = mappers.get(key);
//5.判斷是否有mapper
if (mapper == null) {
throw new IllegalArgumentException("傳入參數有誤");
}
//6.調用工具類執行查詢所有
return new Executor().selectList(mapper,conn);
}
}
Executor 工具類
//負責執行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();
}
}
}
}
五、運行結果及總結
上述實現了查詢數據庫功能
User{id=1, name='張三', pwd='123'}
User{id=2, name='李四', pwd='128'}
Process finished with exit code 0
上述代碼按照去除了Mybatis的依賴,從測試類開始一步一步搭建起來的,讀者也可以自己練習一下