到mybatis的官网进行源码下载:https://mybatis.org/mybatis-3/,
我们选择Source code下载
下载后解压,该项目是一个maven项目,我们用idea打开,目录结构如下
我们在源码工程下创建一个demo目录,存放我们的demo代码
MybatisMain.java
public class MybatisMain { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); Blog blog = sqlSession.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101); System.out.println(blog.getContext()); } }
Blog.java
public class Blog { private Integer id; private String username; private String context; //省去了getter和setter }
mybatis-config.xml
<?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="jdbc.properties"/> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/BlogMapper.xml"/> </mappers> </configuration>
jdbc.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test username=root password=root
BlogMapper.xml
<?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="org.mybatis.example.BlogMapper"> <select id="selectBlog" resultType="org.apache.ibatis.demo.Blog"> select * from Blog where id = #{id} </select> </mapper>
最后需要注意的是我们要把pom文件中的如下部分注释掉,要不然运行会报错。
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> <!--<scope>test</scope>注释掉--> </dependency>
同时,我们要有一个mysql实例,配置见jdbc.properties
mysql> use test Database changed mysql> select * from blog; +------+----------+---------+ | id | username | context | +------+----------+---------+ | 101 | szj | hello | +------+----------+---------+ 1 row in set (0.00 sec) mysql>
运行结果
"C:\Program Files (x86)\Java\jdk1.8.0_181\bin\java" ... log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary. hello Process finished with exit code 0
下一节我们将剖析以上示例的运行原理