MyBatis框架入门(一)

MyBatis框架介绍

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

MyBatis主要完成两件事:

1.根据JDBC规范建立与数据库的连接

2.通过反射打通Java对象与数据库参数交互之间相互转化的关系

MyBatis框架的设计策略

MyBits框架的一个重要组成部分就是其SqlMap配置文件,SqlMap配置文件的核心是Statement语句包括CIUDMyBits通过解析SqlMap配置文件得到所有的Statement执行语句,同时会形成ParameterMapResultMap两个对象,用于处理参数和经过解析后交给数据库处理的SQL对象

核心组件

MyBatis的核心组件包括:SqlSessionFactoryBuilder(构造器)、SqlSessionFactory(工厂接口)、SqlSession(会话接口)、SQL Mapper(映射器)。

SqlSessionFactoryBuilder(构造器)

SqlSessionFactoryBuilder类根据配置信息或者代码来生成SqlSessionFactory,其重载build方法三种。别是InputStream(字节流)、Reader(字符流)、Configuration(类),字节流和字符流都是通过读取XML配置文件的形式创建SqlSessionFactory,而Configuration采用的是java代码方式创建SqlSessionFactory,我们一般常用的是读取配置文件的形式。

SqlSessionFactory(工厂接口)

SqlSessionFactory负责生产SqlSession会话,它有两个实现类,分别是SqlSessionManager和DefaultSqlSessionFactory。一般而言是由DefaultSqlSessionFactory实现的。SqlSessionManager使用在多线程的环境中,它的具体实现依靠DefaultSQLSessionFactory。

SqlSession(会话接口)

SqlSession有两个作用,1)获取映射器,让映射器通过命名空间和方法名称找到对应的SQL,发送给数据库执行后返回结果;2)通过update、insert、select、delete等方法,带上SQL的id来操作在XML中配置好的SQL,从而完成工作,与此同时它也支持事务,通过commit、rollback方法提交或者回滚事务。

SQL Mapper(映射器)

SQL Mapper有四个作用:1)定义参数、2)描述缓存、3)描述SQL语句、4)定义查询结果和POJO的映射关系

代码实现

本篇Demo基于MyBatis,mysql5.7;
Github地址:https://github.com/The-ProgramLife/Demo/tree/master/Mybatis
数据库的增删改查(CRUD)

创建数据库
create database mybatis;

创建表

CREATE TABLE category (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(32) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
插入数据
INSERT INTO category_ VALUES (null,'category1');
INSERT INTO category_ VALUES (null,'category2');

创建一个Java Maven Project


在pom.xml引入MyBatis和MySQL依赖

		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.46</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.6</version>
		</dependency>
创建实体类
实体类Category用于映射数据库中的表category
package pojo;
 
public class Category {
    private int id;
    private String name;
    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;
    }
     
}

在同一个包中配置Category.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="pojo">
	<!-- id: listCategory 进行标示以供后续代码调用。resultType="Category" 表示返回的数据和Category关联起来 -->
	<!-- 查 -->
	<select id="listCategory" resultType="Category">
		select * from Category
	</select>

	<!-- 增 -->
	<insert id="addCategory" parameterType="Category">
		insert into category
		(name) values (#{name})
	</insert>

	<!-- 删 -->
	<delete id="deleteCategory" parameterType="Category">
		delete from category
		where id = #{id}
	</delete>

	<!-- 条件查 -->
	<select id="getCategory" parameterType="int" resultType="Category">
		select *
		from category where id= #{id}
	</select>

	<!-- 改 -->
	<update id="updateCategory" parameterType="Category">
		update category set
		name=#{name} where id=#{id}
	</update>

	<!-- 模糊查 -->
	<select id="listCategoryByName" parameterType="string"
		resultType="Category">
		select * from category where name like concat('%',#{0},'%')
	</select>

	<!-- 多条件查 -->
	<select id="listCategoryByIdAndName" parameterType="map"
		resultType="Category">
		select * from category where id> #{id} and name like
		concat('%',#{name},'%')
	</select>
</mapper>

src/main/java目录下配置mybatis-config.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>
    <typeAliases>
      <package name="pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost/mybatis?characterEncoding=utf8&useSSL=true"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="pojo/Category.xml"/>
    </mappers>
</configuration>

这份代码相信不用作多解释,相当于Hibernate的hibernate.cfg.xml配置文件

在主类中编写运行逻辑

基本步骤

1.获取输入流加载配置文件

2.通过SqlSessionFactoryBuilder()的build()方法载入输入流构建SqlSessionFactory

3.通过SqlSessionFactory的openSession()方法返回一个SqlSession

4.提交SqlSession

5.关闭SqlSession

6.关闭输入流

public class App {
	public static void main(String[] args) throws IOException {

		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();

		// 添加数据
		Category category = new Category();
		category.setName("Category3");
		session.insert("addCtegory", category);

		// 删除数据
		Category category = new Category();
		category.setId(3);
		session.delete("deleteCategory", category);

		// 获取数据
		Category category = session.selectOne("getCategory", 1);
		System.out.println(category.getName());

		// 更新数据
		Category category = session.selectOne("getCategory", 1);
		category.setName("更新的Category");
		session.update("updateCategory", category);

		// 模糊查询
		List<Category> categories = session.selectList("listCategoryByName", "2");
		for (Category category : categories) {
			System.out.println(category.getName());
		}

		// 多条件 查询
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", 1);
		map.put("name", "cat");
		List<Category> categories = session.selectList("listCategoryByIdAndName", map);
		for (Category category : categories) {
			System.out.println(category.getName());
		}
		session.commit();
		session.close();

		inputStream.close();
	}


猜你喜欢

转载自blog.csdn.net/the_programlife/article/details/80602181