學習一個新的組件,一要看須要哪些JAR包,二要看須要哪些配置,三要看API如何使用。java
0、準備Emp數據表mysql
MySQL語法web
create table emp( id int(5) primary key, name varchar(10), sal double(8,2) );
Oracle語法sql
create table emp( id number(5) primary key, name varchar2(10), sal number(8,2) );
一、新建web工程,添加jar
數據庫
須要的jar包包括三部分:mybatis的jar包、mybatis依賴的jar包、數據庫驅動包
apache
我使用的mybatis版本是mybatis-3.2.7session
mybatis | mybatis-3.2.7.jar |
mybatis的依賴包 | 位於lib目錄下mybatis asm-3.3.1.jarapp cglib-2.2.2.jaride commons-logging-1.1.1.jar log4j-1.2.17.jar |
數據庫驅動 | MySQL mysql-connector-java-5.1.38-bin.jar 或 Oracle ojdbc5.jar |
log4j的配置文件,放到src目錄下
log4j.properties
log4j.rootLogger=debug,stdout,logfile log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout log4j.appender.logfile=org.apache.log4j.FileAppender log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n log4j.logger.com.ibatis=DEBUG log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
二、建立Emp.java
Emp.java
package com.rk.entity; public class Emp { private Integer id; private String name; private Double sal; public Emp(){} public Emp(Integer id, String name, Double sal) { this.id = id; this.name = name; this.sal = sal; } 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 Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } }
三、在entity包下添加EmpMapper.xml文件
EmpMapper.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"> <!-- namespace屬性是名稱空間,必須惟一 --> <mapper namespace="mynamespace"> <!-- insert標籤:要書寫insert這麼一個sql語句 id屬性:爲insert這麼一個sql語句取一個任意惟一的名字 parameterType:要執行的dao中的方法的參數,若是是類的話,必須使用全路徑類 --> <insert id="add1"> insert into emp(id,name,sal) values(1,'Tomcat',800) </insert> <!-- 這裏用的是類的全路徑:com.rk.entity.Emp --> <insert id="add2" parameterType="com.rk.entity.Emp"> insert into emp(id,name,sal) values(#{id},#{name},#{sal}); </insert> </mapper>
四、在src目錄下建立mybatis.xml文件
mybatis.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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/testdb"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/rk/entity/EmpMapper.xml"/> </mappers> </configuration>
五、在utils包下添加MyBatisUtils.java,並進行測試是否可以鏈接數據庫
MyBatisUtils.java
package com.rk.utils; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtils { private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); private static SqlSessionFactory sqlSessionFactory; static{ try { Reader reader = Resources.getResourceAsReader("mybatis.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } private MyBatisUtils() {} public static SqlSession getSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession == null){ sqlSession = sqlSessionFactory.openSession(); threadLocal.set(sqlSession); } return sqlSession; } public static void closeSqlSession(){ SqlSession sqlSession = threadLocal.get(); if(sqlSession != null){ sqlSession.close(); threadLocal.remove(); } } public static void main(String[] args) { Connection conn = MyBatisUtils.getSqlSession().getConnection(); System.out.println(conn!=null ? "鏈接成功" : "鏈接失敗"); } }
MyBatisUtils工具類的做用
1)在靜態初始化塊中加載mybatis配置文件和EmpMapper.xml文件
2)使用ThreadLocal對象讓當前線程與SqlSession對象綁定在一塊兒
3)獲取當前線程中的SqlSession對象,若是沒有的話,從SqlSessionFactory對象中獲取SqlSession對象
4)關閉SqlSession,首先獲取當前線程中的SqlSession對象,再將其關閉,釋放其佔用的資源
六、在dao包下添加EmpDao.java,並進行測試
EmpDao.java
package com.rk.dao; import org.apache.ibatis.session.SqlSession; import com.rk.entity.Emp; import com.rk.utils.MyBatisUtils; public class EmpDao { /** * 添加員工(無參數) */ public void add1() throws Exception { SqlSession sqlSession = null; try{ sqlSession = MyBatisUtils.getSqlSession(); //事務開始(默認) //讀取EmpMapper.xml映射文件中的SQL語句 int i = sqlSession.insert("mynamespace.add1"); System.out.println("本次操做影響"+i+"行數據"); //事務提交 sqlSession.commit(); } catch(Exception e){ e.printStackTrace(); if(sqlSession != null){ //事務回滾 sqlSession.rollback(); } } finally{ MyBatisUtils.closeSqlSession(); } } /** * 添加員工(帶參數) */ public void add2(Emp emp) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MyBatisUtils.getSqlSession(); //事務開始(默認) //讀取EmpMapper.xml映射文件中的SQL語句 int i = sqlSession.insert("mynamespace.add2",emp); System.out.println("本次操做影響"+i+"行數據"); //事務提交 sqlSession.commit(); } catch(Exception e){ e.printStackTrace(); if(sqlSession != null){ //事務回滾 sqlSession.rollback(); } } finally{ MyBatisUtils.closeSqlSession(); } } public static void main(String[] args) throws Exception { EmpDao dao = new EmpDao(); dao.add1(); dao.add2(new Emp(2,"小明",500D)); } }
輸出:
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl' adapter. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - PooledDataSource forcefully closed/removed all connections. DEBUG - Opening JDBC Connection DEBUG - Created connection 236749989. DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - ==> Preparing: insert into emp(id,name,sal) values(1,'Tomcat',800) DEBUG - ==> Parameters: DEBUG - <== Updates: 1 本次操做影響1行數據 DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - Returned connection 236749989 to pool. DEBUG - Opening JDBC Connection DEBUG - Checked out connection 236749989 from pool. DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - ==> Preparing: insert into emp(id,name,sal) values(?,?,?); DEBUG - ==> Parameters: 2(Integer), 小明(String), 500.0(Double) DEBUG - <== Updates: 1 本次操做影響1行數據 DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@e1c84a5] DEBUG - Returned connection 236749989 to pool.
七、MyBatis工做流程
1)經過Reader對象讀取src目錄下的mybatis.xml配置文件(該文件的位置和名字能夠任意)
2)經過SqlSessionFactoryBuilder對象建立SqlSessionFactory對象
3)從當前線程中獲取SqlSession對象
4)事務開始,在mybatis中默認
5)經過SqlSession對象讀取EmpMapper.xml映射文件中的操做編號,從而讀取sql語句
6)事務提交(必寫)
7)關閉SqlSession對象,而且分開當前線程與SqlSession對象,讓GC儘早回收