MyBatis 是一個持久層框架,實現了對JDBC操做的封裝,主要用於簡化JDBC操做中的一些相對繁瑣的步驟,例如參數的映射,結果集的映射等。java
1.添加依賴mysql
MYSQL驅動依賴 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> Mybatis框架依賴 <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency>
2.配置項目
在resource下建立mybatis-config.xmlsql
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- mybatis 核心配置 --> <configuration> <!-- 配置初始化環境(鏈接) --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <!-- 使用mybatis自帶鏈接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///jtsys"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment>
</environments>
</configuration>
3.測試程序數據庫
public class TestMybatis { /** * 藉助此對象建立SqlSession(經過此對象 * 實現與數據庫之間的會話) */ protected SqlSessionFactory factory; /** * 此方會在@Test註解修飾的方法以前執行, * 一般用於作一些初始化操做(方法名本身定義) */ @Before public void init()throws IOException{ InputStream in=Resources.getResourceAsStream("mybatis-configs.xml"); factory=new SqlSessionFactoryBuilder().build(in); //系統底層建造者模式構建工廠對象(此對象構建過程相對複雜) System.out.println(factory); } @Test public void testSqlSessionConnection(){ SqlSession session=factory.openSession(); Connection conn=session.getConnection(); System.out.println(conn); }
}apache
4.測試結果session
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@516be40f com.mysql.jdbc.JDBC4Connection@7e0b85f9
在Resource下建立Mapper folder,並建立mybatis配置文件SysLogMapper.xmlmybatis
<?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="com.company.SysLogMapper"> <cache/> <delete id="deleteObject"> delete from sys_logs where id=#{id} </delete> <select id="findPageObject" resultType="Object"> select id,createdTime from sys_logs limit #{startIndex},#{pageSize} </select> </mapper>