Mybatis学习系列(一)入门简介
MyBatis简介
Mybatis是Apache的一个Java开源项目,是一个支持动态Sql语句的持久层框架。Mybatis可以将Sql语句配置在XML文件中,避免将Sql语句硬编码在Java类中。与JDBC相比:
- Mybatis通过参数映射方式,可以将参数灵活的配置在SQL语句中的配置文件中,避免在Java类中配置参数(JDBC)
- Mybatis通过输出映射机制,将结果集的检索自动映射成相应的Java对象,避免对结果集手工检索(JDBC)
- 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学习系列(一)入门简介的更多相关文章
- MyBatis学习系列三——结合Spring
目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring MyBatis在项目中应用一般都要结合Spring,这一章主要把MyBat ...
- MyBatis学习系列二——增删改查
目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...
- MyBatis学习系列一之环境搭建
目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 学习一个新的知识,首先做一个简单的例子使用一下,然后再逐步深入.MyBat ...
- SpringBoot学习笔记(一)入门简介
一.SpringBoot 入门简介 整体讲解内容概况: 1.1 简介 简化Spring应用开发的一个框架: 整个Spring技术栈的一个大整合: J2EE开发的一站式解决方案. Spring Boot ...
- MyBatis学习(一)简介及入门案例
1.什么是MyBatis? MyBatis是一个支持普通SQL查询,存储过程,和高级映射的优秀持久层框架.MyBatis去掉了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装.MyBati ...
- mybatis学习系列一(mybatis简介/使用)
1mybatis简介(1) 1.1工具:jbbc,jdbctemplate 功能简单,sql语句编写在java代码里面,硬编码高耦合的方式 1.2 框架:整体解决方案 1.2.1 Hibernate: ...
- Spring学习系列(一) Spring简介
Spring简介 之前一直想写点东西,可一直没有开始实施,各种原因都有,最大原因可能还是自己太懒了,嘿嘿.最近在看Spring in action这本书,为了能让自己坚持下去把书看完,这次决定同步的在 ...
- mybatis学习系列一
1引入dtd约束(6) Mybatis git地址:https://github.com/mybatis/mybatis-3/wiki/Maven 指导手册:http://www.mybatis.or ...
- MongoDB学习系列(1)--入门介绍
MongoDB是一款为Web应用程序设计的面向文档结构的数据库系统. MongoDB贡献者是10gen公司.地址:http://www.10gen.com 1.MongoDB主要特性: 1.1文档数据 ...
随机推荐
- 解决model属性与系统重名
.h .m + (NSDictionary *)replacedKeyFromPropertyName { return @{ @"detailId" : @"id&qu ...
- MySQL的数据类型(二)
MySQL中提供了多种对字符数据的存储类型,不同的版本可能有所差异.以5.0版本为例,MySQL包括了CHAR.VARCHAR.BINARY.VARBINARY.BLOB.TEXT等多种字符串类型. ...
- 原生js瀑布流
HTML部分代码............................... CSS部分代码........................... 原生js部分代码................. ...
- Java入门(一)
一.语言分类 机器语言 汇编语言 高级语言 二.Java分类 JavaSE 标准版,主要针对桌面应用 JavaEE 企业版,主要针对服务器端的应用 JavaME 微型版,主要针对消费性电子产品的应用 ...
- 基于socketserver模块实现并发的套接字(tcp、udp)
tcp服务端:import socketserver class MyHandler(socketserver.BaseRequestHandler): def handle(self): #通信循环 ...
- js 判断两个时间相差的天数
judgeDay(sDate1, sDate2) { const sDate1 = `${new Date(sDate1).getFullYear()}-${new Date(sDate1).getM ...
- jQuery(二)事件
鼠标事件: click dblclick mouseenter:鼠标进入 mouseleave:鼠标离开 hover:鼠标悬停 <!DOCTYPE html> <html> & ...
- Java : java基础(1)
java编译器有常亮优化机制,如果是常量的计算,会直接判断常量计算结果的取值范围,如果是变量,则没办法判断计算取值范围,编译会异常(如两个byte类型的变量相加). java中的常量指的是用 stat ...
- JS正则表达式笔记
正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串.将匹配的子串替换或者从某个串中取出符合某个条件的子串等. 正则 描述 ...
- python, pycharm, virtualenv 的使用
创建虚拟环境,一次安装多个库 pip freeze > requirements.txt (库的名字都在里面) 产生requirements.txt文件 在另一个环境下使用 pip instal ...