使用的是用配置文件来实现。
配置文件的generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="default" targetRuntime="这里选择合适的引擎">
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 不输出注释 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/local"
userId="root"
password="root">
</jdbcConnection>
<!-- 不强制把所有的数字类型转化为BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<javaModelGenerator targetPackage="club.throwable.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="mappings" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="这里选择合适的Mapper类型" targetPackage="club.throwable.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table tableName="t_order"
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false"
domainObjectName="Order"
mapperName="OrderMapper">
<generatedKey column="id" sqlStatement="MySql"/>
</table>
</context>
</generatorConfiguration>
有两种方式来运行,
第一种,在maven中选择plugins,右击Mybatis-generator:generate,选择 run maven build。
第二种,编写一个Java类
public void RunMbg() throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//mbg.xml配置文件
File configFile = new File("src/main/resources/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
遇到的问题:
1. 报错:
1251:Client does not support authentication protocol requested by server
客户端不支持服务器请求的身份验证协议,考虑升级mysql客户端。
修改方法:
找到你的MySQL安装路径,进入bin目录下:
在这里输入cmd进行命令行:
输入命令mysql -u root -p,进入MySQL数据库
依次输入两条命令:
# 这里最后的root就是你修改后的密码,根据自己的需求更改
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
# 刷新权限
FLUSH PRIVILEGES;
注:每一条命令执行完都出现了Query OK, 0 rows affected也就修改成功了,之后我们就可以正常连接了。
转载于:https://zhuanlan.zhihu.com/p/355385276
2. 报错:
java.sql.SQLException: Unknown initial character set index '255' received from server. Initial client character set can be forced via the 'characterEncoding' property.
报错原因:错误信息表明是字符集的问题。
修改方法:
//修改后
"jdbc:mysql://localhost:3306/testmysql?characterEncoding=utf8";