MyBatis简介

Mybatis是Apache的一个Java开源项目,是一个支持动态Sql语句的持久层框架。Mybatis可以将Sql语句配置在XML文件中,避免将Sql语句硬编码在Java类中。与JDBC相比:

  1. Mybatis通过参数映射方式,可以将参数灵活的配置在SQL语句中的配置文件中,避免在Java类中配置参数(JDBC)
  2. Mybatis通过输出映射机制,将结果集的检索自动映射成相应的Java对象,避免对结果集手工检索(JDBC)
  3. Mybatis可以通过Xml配置文件对数据库连接进行管理。

MyBatis整体架构及运行流程

Mybatis整体构造由 数据源配置文件、Sql映射文件、会话工厂、会话、执行器和底层封装对象组成。

1.数据源配置文件

通过配置的方式将数据库的配置信息从应用程序中独立出来,由独立的模块管理和配置。Mybatis的数据源配置文件包含数据库驱动、数据库连接地址、用户名密码、事务管理等,还可以配置连接池的连接数、空闲时间等。

一个SqlMapConfig.xml基本的配置信息如下:

<configuration>
<!-- 加载数据库属性文件 -->
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<!--使用JDBC实务管理-->
<transactionManager type="JDBC"></transactionManager>
<!--连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
</configuration>

2.Sql映射文件

Mybatis中所有数据库的操作都会基于该映射文件和配置的sql语句,在这个配置文件中可以配置任何类型的sql语句。框架会根据配置文件中的参数配置,完成对sql语句以及输入输出参数的映射配置。

Mapper.xml配置文件大致如下:

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sl.dao.ProductDao">
<!-- 根据id查询product表
resultType:返回值类型,一条数据库记录也就对应实体类的一个对象
parameterType:参数类型,也就是查询条件的类型
-->
<select id="selectProductById" resultType="com.sl.po.Product" parameterType="int">
<!-- 这里和普通的sql 查询语句差不多,对于只有一个参数,后面的 #{id}表示占位符,里面不一定要写id,写啥都可以,但是不要空着,如果有多个参数则必须写pojo类里面的属性 -->
select * from products where id = #{id}
</select>
</mapper>

3.会话工厂与会话

Mybatis中会话工厂SqlSessionFactory类可以通过加载资源文件,读取数据源配置SqlMapConfig.xml信息,从而产生一种可以与数据库交互的会话实例SqlSession,会话实例SqlSession根据Mapper.xml文件中配置的sql,对数据库进行操作。

4.运行流程

会话工厂SqlSessionFactory通过加载资源文件获取SqlMapConfig.xml配置文件信息,然后生成可以与数据库交互的会话实例SqlSession。会话实例可以根据Mapper配置文件中的Sql配置去执行相应的增删改查操作。在SqlSession会话实例内部,通过执行器Executor对数据库进行操作,Executor依靠封装对象Mappered Statement,它分装了从mapper.xml文件中读取的信息(sql语句,参数,结果集类型)。Mybatis通过执行器与Mappered Statement的结合实现与数据库的交互。

执行流程图:

测试工程搭建

1. 新建maven工程

2. 添加依赖pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sl</groupId>
<artifactId>mybatis-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<junit.version>4.12</junit.version>
<mybatis.version>3.4.1</mybatis.version>
<mysql.version>5.1.32</mysql.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<!-- <scope>test</scope> -->
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- 日志处理 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</project>

3.编写数据源配置文件SqlMapConfig.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>
<!-- 加载配置文件 -->
<properties resource="db.properties"></properties>
<environments default="development">
<!-- id属性必须和上面的defaut一致 -->
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<!--dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象源 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!—申明mapper文件 -->
<mappers>
<!-- xml实现 注册productMapper.xml文件 -->
<mapper resource="mapper/productMapper.xml"></mapper>
</mappers>
</configuration>

4.编写SQL映射配置文件productMapper.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">
<mapper namespace="com.sl.mapper.ProductMapper"> <select id="selectAllProduct" resultType="com.sl.po.Product">
select * from products
</select> </mapper>

5.编写测试代码TestClient.java

//使用productMapper.xml配置文件
public class TestClient { //定义会话SqlSession
SqlSession session =null; @Before
public void init() throws IOException {
//定义mabatis全局配置文件
String resource = "SqlMapConfig.xml"; //加载mybatis全局配置文件
//InputStream inputStream = TestClient.class.getClassLoader().getResourceAsStream(resource); InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);
//根据sqlSessionFactory产生会话sqlsession
session = factory.openSession();
} //查询所有user表所有数据
@Test
public void testSelectAllUser() {
String statement = "com.sl.mapper.ProductMapper.selectAllProduct";
List<Product> listProduct =session.selectList(statement);
for(Product product:listProduct)
{
System.out.println(product);
}
//关闭会话
session.close();
} }
public class Product {
private int Id;
private String Name;
private String Description;
private BigDecimal UnitPrice;
private String ImageUrl;
private Boolean IsNew; public int getId() {
return Id;
} public void setId(int id) {
this.Id = id;
} public String getName() {
return Name;
} public void setName(String name) {
this.Name = name;
} public String getDescription() {
return Description;
} public void setDescription(String description) {
this.Description = description;
} public BigDecimal getUnitPrice() {
return UnitPrice;
} public void setUnitPrice(BigDecimal unitprice) {
this.UnitPrice = unitprice;
} public String getImageUrl() {
return Name;
} public void setImageUrl(String imageurl) {
this.ImageUrl = imageurl;
} public boolean getIsNew() {
return IsNew;
} public void setIsNew(boolean isnew) {
this.IsNew = isnew;
} @Override
public String toString() {
return "Product [id=" + Id + ", Name=" + Name + ", Description=" + Description
+ ", UnitPrice=" + UnitPrice + ", ImageUrl=" + ImageUrl + ", IsNew=" + IsNew+ "]";
}
}

6.运行测试用例

Mybatis学习系列(一)入门简介的更多相关文章

  1. MyBatis学习系列三——结合Spring

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring MyBatis在项目中应用一般都要结合Spring,这一章主要把MyBat ...

  2. MyBatis学习系列二——增删改查

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...

  3. MyBatis学习系列一之环境搭建

    目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 学习一个新的知识,首先做一个简单的例子使用一下,然后再逐步深入.MyBat ...

  4. SpringBoot学习笔记(一)入门简介

    一.SpringBoot 入门简介 整体讲解内容概况: 1.1 简介 简化Spring应用开发的一个框架: 整个Spring技术栈的一个大整合: J2EE开发的一站式解决方案. Spring Boot ...

  5. MyBatis学习(一)简介及入门案例

    1.什么是MyBatis? MyBatis是一个支持普通SQL查询,存储过程,和高级映射的优秀持久层框架.MyBatis去掉了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBati ...

  6. mybatis学习系列一(mybatis简介/使用)

    1mybatis简介(1) 1.1工具:jbbc,jdbctemplate 功能简单,sql语句编写在java代码里面,硬编码高耦合的方式 1.2 框架:整体解决方案 1.2.1 Hibernate: ...

  7. Spring学习系列(一) Spring简介

    Spring简介 之前一直想写点东西,可一直没有开始实施,各种原因都有,最大原因可能还是自己太懒了,嘿嘿.最近在看Spring in action这本书,为了能让自己坚持下去把书看完,这次决定同步的在 ...

  8. mybatis学习系列一

    1引入dtd约束(6) Mybatis git地址:https://github.com/mybatis/mybatis-3/wiki/Maven 指导手册:http://www.mybatis.or ...

  9. MongoDB学习系列(1)--入门介绍

    MongoDB是一款为Web应用程序设计的面向文档结构的数据库系统. MongoDB贡献者是10gen公司.地址:http://www.10gen.com 1.MongoDB主要特性: 1.1文档数据 ...

随机推荐

  1. Webpack4 学习笔记八 开发环境和生产环境配置

    webpack resolve属性 webpack 区分开发环境和生产环境 webpack resolve属性 该选项的作用是设置模块如何被解析. resolve.alias: 设置别名, 在vue中 ...

  2. foreach, for in, for of 之间的异同

    forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数. 注意: forEach() 对于空数组是不会执行回调函数的. 示例代码: var arr = [4, 9, 16, 25]; ...

  3. 【Nowcoder 上海五校赛】1 + 2 = 3?(斐波那契规律)

    题目描述 小Y在研究数字的时候,发现了一个神奇的等式方程,他屈指算了一下有很多正整数x满足这个等式,比如1和2,现在问题来了,他想知道从小到大第N个满足这个等式的正整数,请你用程序帮他计算一下. (表 ...

  4. SPOJ PRIME1 - Prime Generator(线性筛)

    Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate ...

  5. vsftpd文件服务参数汇总和虚拟用户使用

    FTP文件传输协议 FTP协议特点 基于C/S结构 双通道协议:数据和命令连接 数据传输格式:二进制(默认)和文本(w文本格式会修改文件内容) 两种模式:服务器角度 主动(PORT style):服务 ...

  6. Python3 operator模块关联代替Python2 cmp() 函数

    Python2 cmp() 函数 描述 cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1. Python ...

  7. myEclipse 常用快捷键,工具等记录

    小的不才,从北大青鸟毕业,出来之后到第一家公司进行工作,当时认为自己很牛逼,很无敌,但是出来之后发现在学校里学的那些东西,在工作中,除了会写一点if...else之外,连循环都很少写. 然而有用的工具 ...

  8. 三角形div原理(小知识点)

    三角形div其实就是从边框的演变过程 #sider2{ width: 100px; height: 100px; border-top: 30px solid #000; border-right:  ...

  9. 事物总线模式实例——EventBus实例详解

    事件总线模式是一种广泛运用于安卓开发之中的一种软件架构模式,而事件总线模式在安卓开发中最广泛的应用莫过于AndroidStudio提供的EventBus,所以我就EventBus来谈谈对事件总线模式的 ...

  10. python中一些内置函数实例

    lambda表达式 简单函数可用lambda表达式 1. def f1() return(123) r1=f1() print() 2. f2=lambda:123 r2=f2() print() 以 ...