MyBatis学习总结(一)——MyBatis入门学习

一、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
posted @ 2018-04-20 07:23  maoyl  阅读(689)  评论(0编辑  收藏  举报