学习一个新的组件,一要看需要哪些JAR包,二要看需要哪些配置,三要看API如何使用。
0、准备Emp数据表
MySQL语法
create table emp( id int(5) primary key, name varchar(10), sal double(8,2) );
Oracle语法
create table emp( id number(5) primary key, name varchar2(10), sal number(8,2) );
1、新建web工程,添加jar
需要的jar包包括三部分:mybatis的jar包、mybatis依赖的jar包、数据库驱动包
我使用的mybatis版本是mybatis-3.2.7
mybatis | mybatis-3.2.7.jar |
mybatis的依赖包 |
位于lib目录下 asm-3.3.1.jar cglib-2.2.2.jar 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
2、创建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; } }
3、在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>
4、在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>
5、在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对象,再将其关闭,释放其占用的资源
6、在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[email protected]] DEBUG - ==> Preparing: insert into emp(id,name,sal) values(1,‘Tomcat‘,800) DEBUG - ==> Parameters: DEBUG - <== Updates: 1 本次操作影响1行数据 DEBUG - Committing JDBC Connection [[email protected]] DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]] DEBUG - Closing JDBC Connection [[email protected]] 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 [[email protected]] 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 [[email protected]] DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]] DEBUG - Closing JDBC Connection [[email protected]] DEBUG - Returned connection 236749989 to pool.
7、MyBatis工作流程
1)通过Reader对象读取src目录下的mybatis.xml配置文件(该文件的位置和名字可以任意)
2)通过SqlSessionFactoryBuilder对象创建SqlSessionFactory对象
3)从当前线程中获取SqlSession对象
4)事务开始,在mybatis中默认
5)通过SqlSession对象读取EmpMapper.xml映射文件中的操作编号,从而读取sql语句
6)事务提交(必写)
7)关闭SqlSession对象,并且分开当前线程与SqlSession对象,让GC尽早回收