1. 配置pom.xml依赖

    <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>

2. 增加db.properties进行记录JDBC相关信息

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=x5

这里需要注意的是url中需要增加参数serverTimezone=UTC,否则会报错

Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.sql.SQLException: 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.
### The error may exist in com/hugh/mybatis/mapper/EmployeesMapper.xml
### The error may involve com.hugh.mybatis.dao.EmployeesMapper.selectByEmployeeID
### The error occurred while executing a query
### Cause: java.sql.SQLException: 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.
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:)
at com.sun.proxy.$Proxy0.selectByEmployeeID(Unknown Source)
at com.hugh.mybatis.App.main(App.java:)
Caused by: java.sql.SQLException: 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.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:)
at java.sql.DriverManager.getConnection(DriverManager.java:)
at java.sql.DriverManager.getConnection(DriverManager.java:)
at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:)
at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:)
at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.getConnection(UnpooledDataSource.java:)
at org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:)
at org.apache.ibatis.datasource.pooled.PooledDataSource.getConnection(PooledDataSource.java:)
at org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:)
at org.apache.ibatis.transaction.jdbc.JdbcTransaction.getConnection(JdbcTransaction.java:)
at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:)
at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:)
... more
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: 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.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:)
at java.lang.reflect.Constructor.newInstance(Constructor.java:)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:)
at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:)
at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:)
at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:)
at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:)
... more

3. 增加Mybatis配置文件

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

这里需要注意的是,假如Mapper类不是和映射文件放在同一个包下,是不能使用<package name=""/>来进行配置的,只有当配置文件和mapper接口同名且在同一包内才可以使用包配置(这个没有进行测试)

4. 配置映射文件

<?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.hugh.mybatis.dao.EmployeesMapper" > <select id="selectByEmployeeID" resultMap="employee">
select
EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, SALARY
from EMPLOYEES
where EMPLOYEE_ID = 100
</select> <resultMap type="com.hugh.mybatis.domain.Employee" id="employee">
<result property="employeeId" column="EMPLOYEE_ID"/>
<result property="firstName" column="FIRST_NAME"/>
<result property="lastName" column="LAST_NAME"/>
<result property="email" column="EMAIL"/>
<result property="salary" column="SALARY"/>
</resultMap>
</mapper>

5. 增加Mapper接口,对应上面配置文件的接口名和方法

package com.hugh.mybatis.dao;

import com.hugh.mybatis.domain.Employee;

public interface EmployeesMapper {

    Employee selectByEmployeeID();
}

6. 使用API

      SqlSessionFactory sf = null;
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sf= new SqlSessionFactoryBuilder().build(inputStream); SqlSession session = sf.openSession();
// 方式1
EmployeesMapper mapper = session.getMapper(EmployeesMapper.class);
System.out.println(mapper.selectByEmployeeID()); // 方式2
System.out.println(session.selectOne("com.hugh.mybatis.dao.EmployeesMapper.selectByEmployeeID")); session.close();

总结:

1.Mybatis框架在使用API时,会先根据Mybatis配置进行加载Configuration对象,从而创建sessionFactory

2.调用API时,可以理解为通过Configuration对象获取对应xml配置进行反射生成Mapper代理类

3.采用方式2进行生成代理类时,并不一定要有对应的接口,也就是采用方式2执行statement时,不需要提供Mapper接口类,只要通过namespace和id定位到statement即可

2019-04-03 搭建Mybatis环境的更多相关文章

  1. Ubuntu18.04下搭建LAMP环境

    一.Apache2 web 服务器的安装 : 可以先更新一下服务器 1.sudo apt-get update             # 获取最新资源包 2.sudo apt-get upgrade ...

  2. 嵌入式开发(一) Ubuntu12.04下搭建交叉编译环境

    操作系统:Ubuntu12.04 AMD64位 交叉编译环境:arm-Linux gcc版本4.4.3 前言: 首先理解一下交叉编译的意思.我们要给嵌入式设备写应用程序,但是又不能在嵌入式设备上完成所 ...

  3. Ubuntu 18.04.1 搭建Java环境和HelloWorld

    一.搭建Java环境 系统环境 Ubuntu 18.04.1 JDK 8 IDEA 2018.2 1.下载JDK 官网地址:http://www.oracle.com/technetwork/java ...

  4. 在Ubuntu 16.04中搭建RobotFramework环境

    1.搭建RF环境 2.安装RF相关库 3.查看RF case 4.设置环境变量 相关知识点:pip  --proxy=http://xx.xx.xx.xx:xx install 包名,使用pip的-- ...

  5. [刘阳Java]_快速搭建MyBatis环境_第2讲

    1.MyBatis的环境配置 导入MyBatis包, mybatis-3.2.8.jar 导入MySQL驱动包, mysql-connector-java-5.1.24-bin.jar 创建表的实体类 ...

  6. Ubuntu 16.04 apt-get搭建LAMP环境

    本文重点介绍在Ubuntu中使用apt-get安装LAMP(Ubuntu 16.04,Apache2.4.18,mysql5.7.12,php7.0.4)环境,所以不再介绍如何安装Ubuntu. 安装 ...

  7. Ubuntu12.04下搭建Java环境

    1.认识需要配置的环境变量 1). PATH: 作用是指定命令搜索路径,打开/etc/environment可以看到PATH变量的值,该变量包含了一系列的路径.那些路径都是一些经常使用的系统命令的目录 ...

  8. Ubuntu16.04下搭建开发环境及编译tiny4412 Android系统【转】

    本文转载自:http://blog.csdn.net/songze_lee/article/details/72808631 版权声明:本文为博主原创文章,未经博主允许不得转载. 1.安装ssh服务器 ...

  9. Ubuntu16.04下搭建LAMP环境

    前期准备sudo apt-get update             # 获取最新资源包sudo apt-get upgrade           # 本机软件全部更新sudo apt-get d ...

随机推荐

  1. 设计模式之Factory模式 代码初见

    ObjectFactory就是通过Factory建造一个Object,比如说DBConnectionFactory就是专门建造DBConnection的工厂 BuilderFactory就是通过Fac ...

  2. js函数前面的+,!

    +function(){}(); 这里的加号,也可以替换成!,~等其他一元操作符,其效果相当于: (function() { console.log("Foo!"); })(); ...

  3. CSS像素、物理像素、逻辑像素、设备像素比、PPI、Viewport

    1.PX(CSS pixels) 1.1 定义 虚拟像素,可以理解为“直觉”像素,CSS和JS使用的抽象单位,浏览器内的一切长度都是以CSS像素为单位的,CSS像素的单位是px. 1.2 注意 在CS ...

  4. 【代码笔记】Web-CSS-CSS 语法

    一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...

  5. 35.Odoo产品分析 (四) – 工具板块(6) – 午餐管理(1)

    查看Odoo产品分析系列--目录 很多公司为都会为员工提供午餐.然而,公司内部的午餐需要适当的管理,特别是在员工或供应商数量非常重要的时候."午餐订单"模块的开发,使管理更容易,也 ...

  6. python 的with用途(清理资源和异常处理,同时代码精简)

    参考如下博客. https://www.cnblogs.com/DswCnblog/p/6126588.html #!/usr/bin/env python # with_example02.py c ...

  7. Easyui datagrid 修改分页组件的分页提示信息为中文

    datagrid 修改分页组件的分页提示信息为中文 by:授客 QQ:1033553122 测试环境 jquery-easyui-1.5.3 问题描述 默认分页组件为英文展示,如下,希望改成中文展示 ...

  8. FT 软件项目管理

    FT 软件项目: 以Feature Team形式组织起来的软件研发项目. 项目是临时组织不是长期组织.  人员临时组织起来, 无组织汇报关系.大家需要充分理解和认同项目的目标,通过项目获得技术.经验. ...

  9. git 的 origin 的含义

    我们从progit 一书中可以看到: 远程仓库名字 “origin” 与分支名字 “master” 一样,在 Git 中并没有任何特别的含义一样. 同时“master”是当你运行git init时默认 ...

  10. C++Primer第五版学习笔记

    <C++ Primer>Learning Note 程序实例下载地址:http://www.informit.com/title/0321714113 第一章            开始 ...