2019-04-03 搭建Mybatis环境
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:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:84) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:58) at com.sun.proxy.$Proxy0.selectByEmployeeID(Unknown Source) at com.hugh.mybatis.App.main(App.java:28) 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:129) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:208) at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:201) at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:196) at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.getConnection(UnpooledDataSource.java:93) at org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:403) at org.apache.ibatis.datasource.pooled.PooledDataSource.getConnection(PooledDataSource.java:89) at org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:138) at org.apache.ibatis.transaction.jdbc.JdbcTransaction.getConnection(JdbcTransaction.java:60) at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:336) at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:85) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) ... 6 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:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2241) at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2265) at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319) at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ... 26 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即可