mybatis
Published:
This is my personal notes for mybatis.
mybatis简介
MyBatis是一个Java持久化框架,它通过XML描述符或注解把对象与存储过程或SQL语句关联起来。
MyBatis可以使开发者在xml文件中编写sql语句并实现数据库的各种操作。
Mybatis的逆向生成工具可以根据数据库的表自动生成 xml文件, pojo类, mapper, 让项目中的数据库操作变得十分简单。
使用Mybatis的逆向生成工具
1 在一个新的工程中打开”mybatis-generatorConfig” / “mybatisGeneratorSqlmapper” 2 逆向生成需要两个java文件: GeneratorDisplay.java 和 MyMapper接口
3 配置generatorConfig.xml文件, 需要注意的地方:
(1) connectionURL 和账号密码的配置
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/imooc-video-dev?useSSL=false&serverTimezone=UTC"
userId="root"
password="xxxxxxxxx">
</jdbcConnection>
(2) 文件生成路径的配置
<!-- 对应生成的pojo所在包 -->
<javaModelGenerator
targetPackage="com.imooc.pojo" targetProject="src/main/java"/>
<!-- 对应生成的mapper所在目录 -->
<sqlMapGenerator
targetPackage="mapper" targetProject="src/main/resources"/>
<!-- 配置mapper对应的java映射 -->
<javaClientGenerator
targetPackage="com.imooc.mapper" targetProject="src/main/java"
(3) 数据库表的配置
在最后的TableName中配置所需要逆向生成的Table就行, Name需要和数据库中的表明一一对应
<table tableName="users"/></table>
<table tableName="comments"/></table>
4 运行GeneratorDisplay.java即可生成xml,pojo,mapper文件
常见错误
1 Could not find or load main class
解决: 重新build maven工程,把所有模块添加进来
2 找不到配置文件generatorConfig.xml
解决: 在IDEA中需要将generatorConfig.xml置于总目录之下,而不是新建的module的目录下
3 java.sql.SQLException: Unknown system variable ‘query_cache_size’
解决: 在pom中更新mysql java connector just update 到最新版, 如 8.0.11
4 The server time zone value ‘EDT’ is unrecognized or represents more than one time zone
解决: 在connectionURL中加上 “serverTimezone=UTC”
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/imooc-video-dev?serverTimezone=UTC"
userId="root"
password="********">
</jdbcConnection>
5 javax.net.ssl.SSLException: closing inbound before receiving peer’s close_notify
解决: 在connectionURL中加上useSSL=false
connectionURL="jdbc:mysql://localhost:3306/imooc-video-dev?useSSL=false&serverTimezone=UTC"
注意: xml文件中&需要用”& amp;”代替