一、MyBatis 简介

MyBatis是一个支持普通SQL查询存储过程高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

二、mybatis + mysql 创建项目

1、创建测试项目,普通java项目或者是JavaWeb项目都可以,

  添加相应的jar包 我用的是mybatis-3.4.5.jar 和 mysql-connector-java-5.1.6.jar

    (本来用的是 mysql-connector-java-6.0.6.jar  出现问题,后面会系统分析)

  如下图所示:

2、创建数据库和表,针对MySQL数据库

  SQL脚本如下:

create database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), job VARCHAR(20),hdate DATE,deptno INT);
INSERT INTO users(NAME, job, hdate, deptno) VALUES('maoyl', 15, 'c++', now());
INSERT INTO users(NAME, job, hdate, deptno) VALUES('spring', 15, 'python', now());

3、添加Mybatis的配置文件conf.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<!--
https://blog.csdn.net/anaini1314/article/details/71157791
<property name="driver" value="com.mysql.jdbc.Driver"/>
异常错误:Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
现在按照最新官方提示支持将com.mysql.jdbc.Driver 改为 com.mysql.cj.jdbc.Driver
--> <!-- ?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
&amp;
-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--
Thu Apr 19 06:50:15 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. -->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments> <mappers>
<!--
注册userMapper.xml文件,
userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml
-->
<mapper resource="com/myl/mapping/userMapper.xml"/>
</mappers> </configuration>

4、实体类User类的代码如下:

package com.myl.entity;

import java.util.Date;

/**
*
* @author myl
* @date 2018年4月20日 上午7:15:04
*
*/ public class User {
private int id;
private String name;
private String job;
private Date hdate;
private int deptno; 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 getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Date getHdate() {
return hdate;
}
public void setHdate(Date hdate) {
this.hdate = hdate;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
} @Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", job=" + job + ", hdate=" + hdate + ", deptno=" + deptno + "]";
} }

5、定义操作users表的sql映射文件userMapper.xml

  创建一个me.myl.mapping包,专门用于存放sql映射文件,在包中创建一个userMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
例如namespace="com.myl.mapping.userMapper"就是com.myl.mapping(包名)+userMapper(userMapper.xml文件去除后缀)
--> <mapper namespace="com.myl.entity.userMapper"> <!--
在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
resultType="com.myl.entity.User"就表示将查询结果封装成一个User类的对象返回
User类就是users表所对应的实体类
-->
<!--
根据id查询得到一个user对象
--> <select id="getUser" parameterType="int" resultType="com.myl.entity.User">
select * from user where id=#{id}
</select> </mapper>

4、在mybatisConf.xml文件中注册userMapper.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<!--
https://blog.csdn.net/anaini1314/article/details/71157791
<property name="driver" value="com.mysql.jdbc.Driver"/>
异常错误:Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
现在按照最新官方提示支持将com.mysql.jdbc.Driver 改为 com.mysql.cj.jdbc.Driver
--> <!-- ?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
&amp;
-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--
Thu Apr 19 06:50:15 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. -->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments> <mappers>
<!--
注册userMapper.xml文件,
userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml
-->
<mapper resource="com/myl/mapping/userMapper.xml"/>
</mappers> </configuration>

6、测试

package com.myl;

import java.io.IOException;
import java.io.Reader; 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 com.myl.entity.User; /**
*
* @author myl
* @date 2018年4月20日 上午7:18:09
* 测试
*/ public class Test { public static void main(String[] args) throws IOException { String conf = "mybatisConf.xml";
Reader reader = Resources.getResourceAsReader(conf);
SqlSessionFactoryBuilder ssfbuild = new SqlSessionFactoryBuilder();
SqlSessionFactory ssf = ssfbuild.build(reader);
SqlSession session = ssf.openSession();
System.out.println(session);
User user;
user = session.selectOne("getUser",1); System.out.println(user); } }

执行结果如下:

遇到问题及解决方案

1、mysql-connector包使用了新的驱动

'com.mysql.jdbc.Driver'驱动类被弃用了,新的驱动类是'com.mysql.cj.jdbc.Driver'。 
这个驱动会通过SPI的方式自动加载,通常不需要人工手动加载。

解决方法1:jdbc.driver的属性值从com.mysql.jdbc.Driver换为com.mysql.cj.jdbc.Driver
解决方法2:在代码中去掉Class.forName(driver);,因为驱动会自动加载。

2、另一个警告

WARN: Establishing SSL connection without server’s identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection
must be established by default if explicit option isn’t set.
For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’.
You need either to explicitly disable SSL by setting useSSL=false,
or set useSSL=true and provide truststore for server certificate verification.

说明:

不推荐不使用服务器身份验证来建立SSL连接。 
如果未明确设置,MySQL 5.5.45+, 5.6.26+ and 5.7.6+版本默认要求建立SSL连接。 
为了符合当前不使用SSL连接的应用程序,verifyServerCertificate属性设置为’false’。 
如果你不需要使用SSL连接,你需要通过设置useSSL=false来显式禁用SSL连接。 
如果你需要用SSL连接,就要为服务器证书验证提供信任库,并设置useSSL=true。

SSL – Secure Sockets Layer(安全套接层)

解决方法

  关于SSL连接的Warning

  再在URL后面添加一个属性useSSL,并设置为false

  jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT&useSSL=false

3.连接的URL中需要增加时区信息

The server time zone value ‘�й���׼ʱ��’ is unrecognized or represents
more than one time zone.
You must configure either the server or JDBC driver (via the serverTimezone configuration property)
to use a more specifc time zone value if you want to utilize time zone support.

服务器的时区值’�й���׼ʱ��’ (就是乱码,可能因为没有设置一个值)不能被识别,或者该值代表了多个时区。 
如果你想获得时区支持的功能,你需要用一个更具体的值来设置服务器或JDBC驱动(通过serverTimezone 属性设置)。

解决方法:

2.连接的URL中需要增加时区信息

  增加serverTimezone属性并设置时区值,测试UTC(世界标准时间)和GMT(格林威治时间)都可以。

  jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT

MyBatis学习总结(一)——MyBatis入门学习的更多相关文章

  1. 学习《零基础入门学习Python》电子书PDF+笔记+课后题及答案

    初学python入门建议学习<零基础入门学习Python>.适合新手入门,很简单很易懂.前一半将语法,后一半讲了实际的应用. Python3入门必备,小甲鱼手把手教授Python,包含电子 ...

  2. Java开发者必备的10大学习网站,送给入门学习java的你,请收下!

    作为开发者来说,必备的除了对编码的热情还要有自己的一套技巧,另外不可缺少的就是平时学习的网站.以下本人收集的 Java 开发者必备的网站,这些网站可以提供信息.以及一些很棒的讲座 , 还能解答一般问题 ...

  3. Spring学习(1)----入门学习(附spring-framework下载地址)

    (一)Spring是什么 Spring是一个开源框架,为了解决企业应用开发的复杂性而创建的,但现在已经不止应用于企业应用 是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器框架- 从大小和开销 ...

  4. asp.net core WebAPI学习以及 发布(***入门学习)

    A asp.net Core 系列[一]——创建Web应用 asp.net Core 系列[二]—— 使用 ASP.NET Core 和 VS2017 for Windows 创建 Web API a ...

  5. cg语言学习&&阳春白雪GPU编程入门学习

    虽然所知甚少,但康大的<GPU编程与Cg编程之阳春白雪下里巴人>确实带我入了shader的门,在里面我第一次清晰地知道了“语义”的意思,非常感谢. 入门shader,我觉得可以先读3本书: ...

  6. 【rocketmq学习笔记】rocketmq入门学习

    基本介绍 rocketmq是阿里巴巴团队使用java语言开发的一款基于发布订阅模型的分布式消息队列中间件,是一款低延迟,高可用,拥有海量消息堆积能力和灵活拓展性的消息队列. 特点 可以实现集群无单点故 ...

  7. MyBatis学习笔记(一)入门

    首先给大家推荐几个网页: http://blog.csdn.net/isea533/article/category/2092001    没事看看 - MyBatis工具:www.mybatis.t ...

  8. MyBatis入门学习教程-使用MyBatis对表执行CRUD操作

    上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...

  9. MyBatis入门学习(二)

    在MyBatis入门学习(一)中我们完成了对MyBatis简要的介绍以及简单的入门小项目测试,主要完成对一个用户信息的查询.这一节我们主要来简要的介绍MyBatis框架的增删改查操作,加深对该框架的了 ...

  10. 【转】MyBatis学习总结(一)——MyBatis快速入门

    [转]MyBatis学习总结(一)——MyBatis快速入门 一.Mybatis介绍 MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC ...

随机推荐

  1. ajax 提交序列化表单

    1.提交序列化表单+参数: var a = $.param({'address':address,'delivity':delivity,'payment':payment}) + '&' + ...

  2. nfs配置项在/etc/exports中的说明

    rw 可读写的权限 ro 只读的权限no_root_squash 登入NFS主机,使用该共享目录时相当于该目录的拥有者,如果是root的话,那么对于这个共享的目录来说,他就具有root的权       ...

  3. 洛谷P1879题解

    题面 显然是个状压DP. 看数据范围,不难发现算法复杂度应该是 \(O(n\times 2^n \times 2^n)\) . 显然第一个 \(n\) 是遍历每一行的土地. 后面两个 \(2^n\) ...

  4. C语言运算符(杂项运算符 ↦ sizeof & 三元)

    实列 1 #include <stdio.h> 2 3 int main() 4 { 5 int a = 4; 6 short b; 7 double c; 8 int* ptr; 9 1 ...

  5. 文件上传之WAF绕过及相安全防护

    文件上传在数据包中可修改的地方 Content-Disposition:一般可更改 name:表单参数值,不能更改 filename:文件名,可以更改 Content-Type:文件 MIME,视情况 ...

  6. 那些 22 岁毕业做Android开发的人,他们 50 岁左右时的人生轨迹是怎样的?

    本人今年35了,已经干了14年程序员,是14年不是13年,因为我是专科毕业. 一直就是普普通通的程序员,特别纯的码农,从没做过管理岗位,并且很可能以后也是如此. 现在已经上有老下有小. 曾经在某著名互 ...

  7. MySQL学习01(初识MySQL)

    初识MySQL 只会写代码的是码农:学好数据库,基本能混口饭吃:在此基础上再学好操作系统和计算机网络,就能当一个不错的程序员.如果能再把离散数学.数字电路.体系结构.数据结构/算法.编译原理学通透,再 ...

  8. 华为应用市场更新APP多次被拒

    最近公司的APP发布了新版本,只进行了线上bug的修复,基本没改什么主体业务功能.各大应用市场都顺利更新上架,但是国货之光华为,被闷了几次.拒来拒去,就是那些反复的内容.内容一般如下: 经检测发现,您 ...

  9. IDM-下载工具

    下载所需要的工具 1.IDM下载地址 链接:https://pan.baidu.com/s/1bHXA0pUYBOAC5f_2Iqvl_g 提取码:lsha 2.IDM破解包下载地址 链接:https ...

  10. 从跨域与同源策略谈CSRF防御与绕过

    之前偶然看到群里有小伙汁问这个token相关的问题,当时我酝酿了一下子,没想好怎么总结,今天来说一下 CSRF在过去还属于OWASP TOP10 ,现在已经不是了(补充一点:关于OWASP API 请 ...