2019-04-03 搭建Mybatis环境

时间:2022-04-14 18:07:01

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即可