注:底层如何获取标签值,请自行研究( 剧透:for循环遍历XML获取标签中的值,然后放入Map )!~
mybatis底层自定义了Executor执行器接口来具体操作数据库,Executor接口有两个实现,一个是基本执行器(默认),一个缓存执行器,SqlSession底层是通过executor接口操作数据库
他是mybatis一个底层封装对象,包装了mybatis配置信息及XXXMapper.xml映射文件等。XXXMapper.xml文件中一个个 select/insert/update/delete标签对应一个Mapped Statement对象 。
原始JDBC和mybatis操作数据库数据,与上面架构图流程相对应。
public class JDBCTest { public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // 加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); // 通过驱动管理类获取数据库链接connection = DriverManager connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root" ); // 定义sql语句 ?表示占位符 String sql = "select * from user where username = ?"; // 获取预处理 statement preparedStatement = connection.prepareStatement(sql); // 设置参数,第一个参数为 sql 语句中参数的序号(从 1 开始),第二个参数为设置的 preparedStatement.setString(1, "王五"); // 向数据库发出 sql 执行查询,查询出结果集 resultSet = preparedStatement.executeQuery(); // 遍历查询结果集 while (resultSet.next()) { System.out.println( resultSet.getString("id") + " " + resultSet.getString("username") ); } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
pom.xml
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cyb</groupId> <artifactId>mybatis</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mybatis Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- mysql依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <finalName>mybatis</finalName> </build> </project>
<?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> <!-- 引入外部配置文件 --> <properties resource="db.properties"></properties> <!-- 数据库链接相关 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> </dataSource> </environment> </environments> <mappers> <!-- 添加映射文件 --> <mapper resource="UserMapper.xml" /> </mappers> </configuration>
db.properties
db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://127.0.0.1:3306/cyb db.username=root db.password=root
<?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"> <!-- namespace:为了分类管理映射文件中的MappedStatement --> <mapper namespace="test"> <select id="queryUserById" parameterType="int" resultType="com.cyb.mybatis.demo.User"> select * from user where id = #{id} </select> </mapper>
package com.cyb.mybatis.demo; import java.util.Date; public class User { private int id; private String username; private Date birthday; private int sex; private String address; public int getId() { return id; } public void setId(int 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 int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", birthday=" + birthday + ", sex=" + sex + ", address=" + address + "]"; } }
package com.cyb.mybatis.demo; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Before; import org.junit.Test; public class MybatisDemo { private SqlSessionFactory sqlSessionFactory; @Before public void init() throws Exception { //指定全局配置文件路径 String resource = "SqlMapConfig.xml"; //加载资源文件(包括全局文件和映射文件) InputStream inputStream = Resources.getResourceAsStream(resource); //使用构建者模式创建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testSelect() { //由SqlSessionFactory工厂去创建SqlSession(会话) SqlSession sqlSession = sqlSessionFactory.openSession(); //调用SqlSession接口,去实现数据库的CRUD User user = sqlSession.selectOne("test.queryUserById", 1); System.out.println(user); //释放资源 sqlSession.close(); } }