MyBatis需要引用的jar包:
maven官网(https://mvnrepository.com/)查询Maven引入MyBatis依赖代码信息
所有依赖:
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>cglibgroupId>
<artifactId>cglibartifactId>
<version>3.2.5version>
dependency>
<dependency>
<groupId>org.ow2.asmgroupId>
<artifactId>asmartifactId>
<version>5.2version>
dependency>
<dependency>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-apiartifactId>
<version>2.3version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.6version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.3version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.25version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.25version>
<scope>testscope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
dependencies>
<configuration>
<environments default="testEM">
<environment id="onlineEM">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
dataSource>
environment>
<environment id="testEM">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/aoing/dao/mapper.xml">mapper>
mappers>
configuration>
<mapper namespace="xxx">
<insert id="insertStudent" parameterType="com.aoing.bean.Student">
insert into student(name,age,score) value(#{name},#{age},#{score})/*必须要和属性同名*/
insert>
mapper>
log4j.properties
log4j.rootLogger=debug, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern= %d{hh:mm:ss,SSS} [%t] %-5p %c %x - %m%n
CREATE DATABASE `test`;
USE `test`;
/*Table structure for table `student` */
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`score` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
insert into `student`(`id`,`name`,`age`,`score`) values (1,'张三',23,93.5),(2,'李四',24,94.5),(3,'王五',25,95.5);
package com.aoing;
import com.aoing.bean.Student;
import com.aoing.dao.StudentDao;
import com.aoing.dao.StudentDaoImpl;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
public class MyTest_log4j
{
private static Logger logger = Logger.getLogger(MyTest_log4j.class);
private StudentDao dao;
@Before
public void before(){
dao = new StudentDaoImpl();
}
@Test
public void testInsert()
{
Student student = new Student("小明", 24, 90);
dao.insertStudent(student);
logger.info("插入数据库");
}
}
package com.aoing.bean;
public class Student {
private Integer id;
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
package com.aoing.dao;
import com.aoing.bean.Student;
public interface StudentDao {
void insertStudent(Student student);
}
package com.aoing.dao;
import com.aoing.bean.Student;
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 java.io.IOException;
import java.io.InputStream;
public class StudentDaoImpl implements StudentDao {
private SqlSession sqlSession;
@Override
public void insertStudent(Student student) {
try{
//加载主配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
//创建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession对象
sqlSession = sqlSessionFactory.openSession();
//进行增删改查
sqlSession.insert("insertStudent",student);
//提交事务
sqlSession.commit();
} catch (IOException e){
e.printStackTrace();
} finally{
if(sqlSession != null){
sqlSession.close();
}
}
}
}
使用junit运行测试类MyTest_log4j的testInsert方法
查看数据库:
package com.aoing.utils;
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 java.io.IOException;
import java.io.InputStream;
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSession getSqlSession(){
try {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
//设为单例模式
if (sqlSessionFactory == null) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
}
return sqlSessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.aoing.dao;
import com.aoing.bean.Student;
import com.aoing.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
public class StudentDaoImpl implements StudentDao {
private SqlSession sqlSession;
@Override
public void insertStudent(Student student) {
try{
//创建SqlSession对象
sqlSession = MyBatisUtils.getSqlSession();
//进行增删改查
sqlSession.insert("insertStudent",student);
//提交事务
sqlSession.commit();
} finally{
if(sqlSession != null){
sqlSession.close();
}
}
}
}
<configuration>
<properties resource="jdbc_mysql.properties"/>
<environments default="onlineEM">
<environment id="onlineEM">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
<environment id="testEM">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper.xml">mapper>
mappers>
configuration>
jdbc_mysql.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=123
在输入流对象使用完毕后,不用手工进行流的关闭。因为输入流在使用完毕后,SqlSessionFactoryBuilder对象的build()方法会自动将输入流关闭。
使用SqlSessionFactory 接口对象的openSession()方法创建SqlSession对象,SqlSessionFactory 接口的实现类为DefaultSqlSessionFactory。
openSession()方法的源码:
由上看出,无参的openSession()方法,将事务的自动提交直接赋值为false。创建SqlSession就是加载了主配置文件,创建一个执行器对象(将来用于执行映射文件中的SQl语句),初始化了一个DB数据被修改的标志变量dirty,关闭了事务的自动提交功能。
对于SqlSession的insert|()、delete()、update()方法,底层均是调用执行了update()方法。
增删改操作均是对数据进行修改,均是将dirty变量设置为true,并且在获取到的映射文件中指定id的SQL语句后,由执行器executor执行。
isCommitOrRollbackRequired(force)方法的返回值为true。继续跟踪executor的commit()方法:
执行SqlSession的无参commit()方法,最终会将事务进行提交。
isCommitOrRollbackRequired(force)方法的返回值为true,继续跟踪executor的close()方法:
再跟踪Executor接口的BaseExecutor抽象类的close()方法:
在SqlSession进行关闭时,会将事务回滚后关闭。所以对于MyBatis程序,无需通过显式地对SqlSession进行回滚,达到事务回滚的目的。