1. MyBatis简介

  MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。

  MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。

  MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

2. MyBatis框架

2.1 MyBatis下载

  MyBatis下载地址:https://github.com/mybatis/mybatis-3

  MyBatis参考文档:http://www.mybatis.org/mybatis-3/getting-started.html

            http://www.mybatis.org/mybatis-3/zh/getting-started.html

2.2 MyBatis基本构成

  MyBatis核心组件:

  ◊ SqlSessionFactoryBuilder:根据配置信息或代码来生成SqlSessionFactory。

  ◊ SqlSessionFactory:生成SqlSession。

  ◊ SqlSession:发送SQL去执行并返回结果,获取Mapper接口。

  ◊ SQL Mapper:由一个Java接口和XML文件(或注解)构成,提供对应的SQL和映射规则。负责发送SQL去执行,并返回结果。

3. MyBatis快速入门

3.1 基于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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>libing</groupId>
<artifactId>com-helloworld-api</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>com-helloworld-api Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies> <build>
<finalName>com-helloworld-api</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

pom.xml

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/helloworld?characterEncoding=utf8
database.username=root
database.password=root

jdbc.properties

<?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="jdbc.properties" /> <environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="mappers/RoleMapper.xml" />
</mappers>
</configuration>

mybatis-config.xml

log4j.rootLogger=DEBUG,stdout

log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

log4j.properties

package com.libing.helloworld.model;

public class Role {

    private Integer id;

    private String roleName;

    public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getRoleName() {
return roleName;
} public void setRoleName(String roleName) {
this.roleName = roleName;
} }

Role.java

package com.libing.helloworld.dao;

import java.util.List;

import com.libing.helloworld.model.Role;

public interface IRoleDao {

    List<Role> findAll();

}

IRoleDao.java

<?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.libing.helloworld.dao.IRoleDao">
<resultMap id="baseResultMap" type="com.libing.helloworld.model.Role">
<id property="id" column="id" />
<result property="roleName" column="role_name" />
</resultMap> <select id="findAll" resultMap="baseResultMap">
SELECT
id,
role_name
FROM
role
ORDER BY id ASC
</select> </mapper>

RoleMapper.xml

package com.libing.helloworld.test;

import java.io.InputStream;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; import com.libing.helloworld.dao.IRoleDao;
import com.libing.helloworld.model.Role; public class RoleTest { SqlSession sqlSession = null; @Before
public void init() {
PropertyConfigurator.configure(RoleTest.class.getClassLoader().getResourceAsStream("log4j.properties"));
String resource = "mybatis-config.xml";
try {
InputStream inputStream = RoleTest.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
} catch (Exception e) {
e.printStackTrace();
}
} @Test
public void findAll() {
try {
IRoleDao roleDao = sqlSession.getMapper(IRoleDao.class);
List<Role> roles = roleDao.findAll(); Assert.assertNotNull(roles);
Assert.assertTrue(roles.size() > 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
} }

RoleTest.java

  选中RoleTest.java,右击 | Run As | JUnit Test,查看运行结果。

DEBUG [main] - ==>  Preparing: SELECT id, role_name FROM role ORDER BY id ASC
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 6

3.2 基于注解实现

<?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>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings> <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:3306/helloworld?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments> <mappers>
<mapper class="com.libing.helloworld.dao.IRoleDao" />
</mappers>
</configuration>
package com.libing.helloworld.dao;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.libing.helloworld.model.Week;

public interface IRoleDao {
@Select("SELECT id,role_name FROM role ORDER BY id ASC")
List<Role> findAll();
}

3.3 mysql-connector-java 6.0.6配置

  pom.xml:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>

  mybatis-config.xml:

<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/helloworld?serverTimezone=UTC&amp;characterEncoding=utf8&amp;useSSL=false" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>

  jdbc.properties:

database.driver=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/helloworld?serverTimezone=UTCcharacterEncoding=utf8&useSSL=false
database.username=root
database.password=root

MyBatis基础:MyBatis入门(1)的更多相关文章

  1. Mybatis基础及入门案例

    这几天正在对SSM框架的知识进行一个回顾加深,有很多东西学的囫囵吞枣,所以利用一些时间进一步的学习.首先大概了解一下mybatis的使用,再通过一个案例来学习它. 什么是MyBatis Mybatis ...

  2. MyBatis基础入门《二十》动态SQL(foreach)

    MyBatis基础入门<二十>动态SQL(foreach) 1. 迭代一个集合,通常用于in条件 2. 属性 > item > index > collection : ...

  3. MyBatis基础入门《十九》动态SQL(set,trim)

    MyBatis基础入门<十九>动态SQL(set,trim) 描述: 1. 问题 : 更新用户表数据时,若某个参数为null时,会导致更新错误 2. 分析: 正确结果: 若某个参数为nul ...

  4. MyBatis基础入门《十八》动态SQL(if-where)

    MyBatis基础入门<十八>动态SQL(if-where) 描述: 代码是在<MyBatis基础入门<十七>动态SQL>基础上进行改造的,不再贴所有代码,仅贴改动 ...

  5. MyBatis基础入门《十七》动态SQL

    MyBatis基础入门<十七>动态SQL 描述: >> 完成多条件查询等逻辑实现 >> 用于实现动态SQL的元素主要有: > if > trim > ...

  6. MyBatis基础入门《十六》缓存

    MyBatis基础入门<十六>缓存 >> 一级缓存 >> 二级缓存 >> MyBatis的全局cache配置 >> 在Mapper XML文 ...

  7. MyBatis基础入门《十五》ResultMap子元素(collection)

    MyBatis基础入门<十五>ResultMap子元素(collection) 描述: 见<MyBatis基础入门<十四>ResultMap子元素(association ...

  8. MyBatis基础入门《十四》ResultMap子元素(association )

    MyBatis基础入门<十四>ResultMap子元素(association ) 1. id: >> 一般对应数据库中改行的主键ID,设置此项可以提高Mybatis的性能 2 ...

  9. MyBatis基础入门《十三》批量新增数据

    MyBatis基础入门<十三>批量新增数据 批量新增数据方式1:(数据小于一万) xml文件 接口: 测试方法: 测试结果: =============================== ...

  10. MyBatis基础入门《十二》删除数据 - @Param参数

    MyBatis基础入门<十二>删除数据 - @Param参数 描述: 删除数据,这里使用了@Param这个注解,其实在代码中,不使用这个注解也可以的.只是为了学习这个@Param注解,为此 ...

随机推荐

  1. 四.js 正则表达式

    一.正则表达式 1.定义:对字符串规则的描述 2.作用:可以检查字符串是否符合规则,可以按规则来截取字符串 3.定义: a.简单模式:var reg = /hello/; b.复杂模式:var reg ...

  2. UIWindow 官方文档解析

    UIWindow定义了一个window对象,其用于管理和协调一个app在设备屏幕上的显示.除非一个app能在外部设备上显示内容,一般就只有一个window. window的主要功能:1)提供一个区域来 ...

  3. redis底层设计(一)——内部数据结构

    redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorted set ...

  4. Java中的并发工具类(CountDownLatch、CyclicBarrier、Semaphore、Exchanger)

    在JDK的并发包里提供了很多有意思的并发工具类.CountDownLatch.CyclicBarrier和Semaphore 工具类提供了一种并发流程控制的手段,Exchanger 工具类则提供了在线 ...

  5. .NET下日志系统的搭建——log4net+kafka+elk

    .NET下日志系统的搭建--log4net+kafka+elk 前言     我们公司的程序日志之前都是采用log4net记录文件日志的方式(有关log4net的简单使用可以看我另一篇博客),但是随着 ...

  6. NO NEWS IS GOOD NEWS

    从客户那传来一个噩耗:要求每个表单在保存之后,要在页面上弹一个 “ 保存成功 ” 的对话框. 客户代表志得意满地说这样用户体验更好,略带谴责意味地傲娇道,“你们早该想到的”.呵呵…… 可不是嘛,我刚入 ...

  7. urllib爬虫(流程+案例)

    网络爬虫是一种按照一定规则自动抓取万维网信息的程序.在如今网络发展,信息爆炸的时代,信息的处理变得尤为重要.而这之前就需要获取到数据.有关爬虫的概念可以到网上查看详细的说明,今天在这里介绍一下使用ur ...

  8. form,ajax注册,logging日志使用

    一.form表单类型提交注册信息 二.ajax版本提交注册信息 <!DOCTYPE html> <html lang="en"> <head> ...

  9. 最值反演 min-max容斥

    说实话这些博客早晚都要整理后上m***999. 最值反演是针对一个集合中最大/最小值的反演. \[ \max\{S\}=\sum_{T\subset S}(-1)^{|T|+1}\min\{T\} \ ...

  10. Makes And The Product CodeForces - 817B (思维+构造)

    B. Makes And The Product time limit per test 2 seconds memory limit per test 256 megabytes input sta ...