Mybatis框架学习1:入门

框架介绍

Mybatis介绍

​ MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis。是一个基于Java的持久层框架。
​ Mybatis本质和Hibernate等持久层框架一样,底层均是基于jdbc的,作用均是实现数据的持久化。

Mybatis和Hibernate对比

对比项 Mybatis Hibernate
底层原理 基于jdbc 基于jdbc
开发速度 业务无复杂查询时较快,上手快 复杂查询语句多时较快。上手慢
sql优化 复杂 手写sql,容易优化
缓存 支持一级、二级缓存,支持第三方缓存 支持一级、更好的二级缓存,支持第三方缓存
可移植性 不同数据库需写不同sql语句 Hibernate负责映射
日志系统 具有自己的日志系统 使用第三方日志工具

准备工作

创建数据

CREATE TABLE `user` (
  `id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `description` text
) ;
INSERT INTO `user` VALUES ('1', 'uzi', 'a gun');
INSERT INTO `user` VALUES ('2', 'the Shy', 'ChampionTop');
INSERT INTO `user` VALUES ('3', 'rookie', 'ChampionMid');
INSERT INTO `user` VALUES ('4', 'clearlove', 'old man');

资源准备

如果创建的是java项目,那么需要下载以下jar包:

  • mybatis-3.4.6.jar

  • commons-logging-1.2.jar

  • log4j-1.2.17.jar

  • asm-5.2.jar

  • cglib-3.2.5.jar

    如果创建的是maven项目,则导入对应依赖即可。

创建项目

我这里创建的是java项目

导入jar包

在项目根目录下创建一个文件夹,命名为lib,将下载好的jar包复制进去后,邮件选中,选择 Buildpath—>add to BuildPath。

a

创建Mybatis配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!--需要导入mybatis的dtd约束文件 -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--
              属性 
        <properties></properties>
             全局参数设置
        <settings></settings>
             类型别名
        <typeAliases></typeAliases>
            类型处理器
        <typeHandles></typeHandles>
            对象工厂
        <objectFactory></objectFactory>
            插件
        <plugins></plugins>
        以上属性现阶段都可以忽视,后面会详细介绍
    -->
    

<!-- 配置mybatis的环境信息 -->

<environments default="development">
    <environment id="development">
        <!-- 配置JDBC事务控制,由mybatis进行管理 -->
        <transactionManager type="JDBC"></transactionManager>
        <!-- 配置数据源,采用dbcp连接池 -->
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>
    <!-- 使用mappers标签加载sql映射文件 -->    
<mappers>
    <!-- 此处根据自己实际的sql映射文件位置来填写-->
    <mapper resource="com/mybatis/mapping/User.xml"/>
</mappers>
</configuration>

创建实体类

  package com.mybatis.domain;
  
  public class User {
  	private int id;
  	private String name;
  	private String description;
  	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;
  	}
  	@Override
  	public String toString() {
  		return "User [id=" + id + ", name=" + name + ", description=" + description+ "]";
  	}
  }

创建sql映射配置文件

<?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">
<!-- namespace:命名空间,对sql进行一个分类管理 -->
<!-- 注意:namespace在mapper代理时,具有重要且特殊的作用 -->
<mapper namespace="com.mybatis.mapping.userMapper">
         <!-- 
 2             使用id进行查询
 3         查询,使用select来表示一个查询的statement,相当于statement.executeQuery
 4         id:表示该statement唯一标识
 5         parameterType:输入参数类型
 6         resultType:输出参数类型,使用的是User类,则会将查询出来的记录封装到该类中
 7         #{id}:使用#{}接收输入的参数,其中的"id"属性名任意,可以为uid,也可以为别的。
 8       -->
 	  <!-- 查询 -->
      <select id="getUser" parameterType="int" resultType="com.mybatis.domain.User">
         SELECT * FROM user WHERE id= #{id}
	   </select>
	   <!-- 插入 -->
	   <insert id="addUser" parameterType="com.mybatis.domain.User">
	   	INSERT INTO user(name,description) VALUES(#{name},#{description})
	   </insert>
	   <!--删除-->
	   <delete id="deleteUser" parameterType="int">
	   DELETE FROM user WHERE id= #{id}
	   </delete>
	   <!-- 更新 -->
	   <update id="updateUser" parameterType="com.mybatis.domain.User">
	   UPDATE user SET name= #{name},description= #{description} WHERE id = #{id}
	   </update>
	   <!--查询所有-->
	   <select id="getAllUsers" resultType="com.mybatis.domain.User">
	   	SELECT * FROM user;
	   </select>
</mapper>

完成简单CRUD

创建一个测试类

/**
 * @Author {LearnAndGet}
 * @Time 2018年12月24日
 * @Discription:
 */
package com.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 org.apache.log4j.Logger;

import com.mybatis.domain.User;

public class Test {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		//1.读取配置文件
		String resource = "SqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		//2.根据配置文件创建SqlSessionFactory
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		//3.SqlSessionFactory创建SqlSession
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		//4.SqlSession执行statement,并返回映射结果
		

		//查询测试
		User user = sqlSession.selectOne("com.mybatis.mapping.userMapper.getUser",1);
		System.out.println(user);
		
		//查询所有
		List users = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users);
		
		//插入测试
		User user2 = new User();
		user2.setName("Knight");
		user2.setDescription("a killer");
		sqlSession.insert("com.mybatis.mapping.userMapper.addUser", user2);
		//再次查询所有
		List users2 = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users2);
		
		//删除测试
		sqlSession.delete("com.mybatis.mapping.userMapper.deleteUser",1);
		//再次查询所有
		List users3 = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users3);
		
		//更新测试(先查出一个后更新)
		User oldUser = sqlSession.selectOne("com.mybatis.mapping.userMapper.getUser",3);
		oldUser.setName("GodV");
		sqlSession.update("com.mybatis.mapping.userMapper.updateUser", oldUser);
		//再次查询所有
		List users4 = sqlSession.selectList("com.mybatis.mapping.userMapper.getAllUsers");
		System.out.println(users4);
				
		sqlSession.close();
	}
}

输出结果如下

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1988859660.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - ==>  Preparing: SELECT * FROM user WHERE id= ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
User [id=1, name=uzi, description=a gun]
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 4
[User [id=1, name=uzi, description=a gun], User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=rookie, description=ChampionMid], User [id=4, name=clearlove, description=old man]]
DEBUG [main] - ==>  Preparing: INSERT INTO user(name,description) VALUES(?,?) 
DEBUG [main] - ==> Parameters: Knight(String), a killer(String)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 5
[User [id=1, name=uzi, description=a gun], User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=rookie, description=ChampionMid], User [id=4, name=clearlove, description=old man], User [id=5, name=Knight, description=a killer]]
DEBUG [main] - ==>  Preparing: DELETE FROM user WHERE id= ? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 4
[User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=rookie, description=ChampionMid], User [id=4, name=clearlove, description=old man], User [id=5, name=Knight, description=a killer]]
DEBUG [main] - ==>  Preparing: SELECT * FROM user WHERE id= ? 
DEBUG [main] - ==> Parameters: 3(Integer)
DEBUG [main] - <==      Total: 1
DEBUG [main] - ==>  Preparing: UPDATE user SET name= ?,description= ? WHERE id = ? 
DEBUG [main] - ==> Parameters: GodV(String), ChampionMid(String), 3(Integer)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: SELECT * FROM user; 
DEBUG [main] - ==> Parameters: 
DEBUG [main] - <==      Total: 4
[User [id=2, name=the Shy, description=ChampionTop], User [id=3, name=GodV, description=ChampionMid], User [id=4, name=clearlove, description=old man], User [id=5, name=Knight, description=a killer]]
DEBUG [main] - Rolling back JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@768b970c]
DEBUG [main] - Returned connection 1988859660 to pool.

总结

由上述步骤来看,使用Mybatis来完成一个入门的数据库查询并不困难,一共有以下几个步骤:

  1. 创建Mybatis的xml配置文件,该配置文件主要约束了Mybatis的行为,包括数据库连接以及sql映射文件位置等
  2. 创建sql映射的配置文件,在该文件中,将指定的sql语句绑定到一个关键字上
  3. 创建SqlSession对象,使用SelectOne方法,执行"命名空间+关键字",并附带一个查询参数,即可完成查询。
posted @ 2018-12-28 09:21  Java_Panda  阅读(615)  评论(3编辑  收藏  举报