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. WEB前端 CSS(非布局)

    目录 WEB前端 CSS CSS引入方式 CSS结构 CSS选择器 直接选择器 组合选择器 分组选择器 也叫并集选择器 属性选择器 伪类选择器 伪元素选择器 CSS选择器是一个查找的过程,高效的查找影 ...

  2. 经典面试题:浏览器是怎样解析CSS的?

    摘要: 理解浏览器原理. 解析 一旦 CSS 被浏览器下载,CSS 解析器就会被打开来处理它遇到的任何 CSS.这可以是单个文档内的 CSS.<style>标记内的 CSS,也可以是 DO ...

  3. 如何高效地遍历 MongoDB 超大集合?

    GitHub 仓库:Fundebug/loop-mongodb-big-collection 本文使用的编程语言是 Node.js,连接 MongoDB 的模块用的是mongoose.但是,本文介绍的 ...

  4. idea使用事项

    1.调用外部jar包 Run/Debug Configurations --- Tomcat Server --- Startup/connection --- Debug 添加“path”变量:** ...

  5. Linux 安装 powershell

    linux 安装 powershell Intro powershell 已经推出了一个 Powershell Core, 版本号对应 Powershell 6.x,可以跨平台,支持 Linux 和 ...

  6. Python第二天 变量 运算符与表达式 input()与raw_input()区别 字符编码 python转义符 字符串格式化 format函数字符串格式化 帮助

    Python第二天  变量  运算符与表达式  input()与raw_input()区别  字符编码  python转义符  字符串格式化  format函数字符串格式化  帮助 目录 Pychar ...

  7. Elasticsearch源码分析 - 源码构建

    原文地址:https://mp.weixin.qq.com/s?__biz=MzU2Njg5Nzk0NQ==&mid=2247483694&idx=1&sn=bd03afe5a ...

  8. WPF中窗体最大化问题处理

    遇到的问题信息 问题:当WindowStyle=None时,窗口最大化,不显示任务栏 -- 即窗体是全屏效果. 解决中遇到的问题列表[主要涉及到任务栏发生改变后的一些问题处理]: 最大化时,任务栏被遮 ...

  9. RESTful API规范

    1. 域名 应该尽量将API部署在专用的域名下. https://api.example.com 如果确定API简单,不会有进一步的括在,可以考虑放在主域名之下. https://example.or ...

  10. SQL UCASE() 函数

    UCASE() 函数 UCASE 函数把字段的值转换为大写. SQL UCASE() 语法 SELECT UCASE(column_name) FROM table_name SQL UCASE() ...