写点什么

mybatis 学习一之入门示例,阿里 + 头条 + 腾讯等大厂 Java 面试题分享

用户头像
极客good
关注
发布于: 刚刚

<settings>


<setting name="logImpl" value="LOG4J2"/>


</settings>


<typeAliases>


<package name="com.zy.entity" />


</typeAliases>


<environments default="development">


<environment id="development">


<transactionManager type="JDBC"/>


<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>


</environments>


<mappers>


<package name="com.zy.mapper" />


</mappers>


</configuration>


代码:




定义 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" ?>


<!DOCTYPE mapper


PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"


"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.huawei.mapper.BlogMapper">


<select id="selectBlog" resultType="Blog">


select * from Blog where id = #{id}


</select>


<select id="insert" parameterType="Blog">


insert into Blog(id, title, author_id, state, featured, style)


values


(#{id}, #{title}, #{authorId}, #{state}, #{featured}, #{style});


</selec


【一线大厂Java面试题解析+核心总结学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
复制代码


t>


</mapper>


定义接口:




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);


}

用户头像

极客good

关注

还未添加个人签名 2021.03.18 加入

还未添加个人简介

评论

发布
暂无评论
mybatis学习一之入门示例,阿里+头条+腾讯等大厂Java面试题分享