-->
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>代码:
定义pojo:
package com.zy.entity;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@Builder(toBuilder = true)
public class Blog {
private Integer id;
private String title;
private int authorId;
private String state;
private Boolean featured;
private String style;
}
Mapper文件:
<?xml version="1.0" encoding="UTF-8" ?>
select * from Blog where id = #{id}
insert into Blog(id, title, author_id, state, featured, style)
values
(#{id}, #{title}, #{authorId}, #{state}, #{featured}, #{style});
定义接口:
package com.zy.mapper;
import com.huawei.entity.Blog;
public interface BlogMapper {
//接口中的方法名必须和mapper中sql语句的id相同
Blog selectBlog(Integer id);
//插入
void insert(Blog blog);
}
对应的类型:
定义DAO:
import com.huawei.entity.Blog;
import com.huawei.mapper.BlogMapper;
import com.huawei.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
public class BlogDao {
private SqlSession sqlSession = MyBatisUtil.getSqlSession();
private BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
public Blog queryBlogById(Integer id) {
return mapper.selectBlog(id);
}
public void insert(Blog blog) {
try {
mapper.insert(blog);
sqlSession.commit();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
工具类的编写:
package com.zy.util;
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.Reader;
public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader(“mybatis/mybatis-config.xml”);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
catch (IOException e) {
e.printStackTrace();
}
}
public MyBatisUtil() {
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
编写测试类:
package com.zy.mapper;
import com.huawei.dao.BlogDao;
import com.huawei.entity.Blog;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
public class BlogMapperTest {
private static final Logger logger = LogManager.getLogger(BlogMapperTest.class);
@Test
public void testSelectBlog() {
Blog blog = new BlogDao().queryBlogById(1);
System.out.println(blog);
logger.info(“blog is:{}”, blog);
}
@Test
public void testInsertBlog() {
Blog build = Blog.builder()
.authorId(1)
.state(“ACTIVE”)
.style(“333”)
.featured(false)
.title(“三国演义”)
.build();
new BlogDao().insert(build);
}
}
运行结果:
问题:
1.为什么代码中的sqlSession需要关闭,但是获取配置文件的Reader不需要关闭呢???
看源码:
查看build()方法:
public SqlSessionFactory build(Reader reader) {
return this.build((Reader)reader, (String)null, (Properties)null);
}
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
SqlSessionFactory var5;
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
var5 = this.build(parser.parse());
} catch (Exception var14) {
throw ExceptionFactory.wrapException(“Error building SqlSession.”, var14);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException var13) {
}
}
return var5;
}
我们发现,reader已经被关闭,因此不需要我们关闭
2.为什么插入数据时,需要手动提交呢???难道不能自动提交吗???
查看SqlSession的创建过程:
sqlSession = sqlSessionFactory.openSession();
进入DefaultSqlSessionFactory:
public SqlSession openSession() {
return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false);
}
我们发现最后一个参数时false,这个参数时干嘛呢???继续往下看
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
DefaultSqlSession var8;
try {
Environment environment = this.configuration.getEnvironment();
TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
Executor executor = this.configuration.newExecutor(tx, execType);
var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
} catch (Exception var12) {
this.closeTransaction(tx);
throw ExceptionFactory.wrapException("Error opening session. Cause: " + var12, var12);
} finally {
ErrorContext.instance().reset();
}
return var8;
}
这个参数,其实就是autoCommit的参数,默认是false,表示不能自动提交,必须手动提交。
那么有没有支持传值的函数呢???
public SqlSession openSession(boolean autoCommit) {
return this.sqlSessionFactory.openSession(autoCommit);
}
显然是存在这样函数的,我们可以自己传参,来设置是否支持自动提交。
我的工具类可以改造为一个抽象类:
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.Reader;
public abstract class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory = null;
private static SqlSession sqlSession = null;
static {