Mybatis自动代码生成
-
引入pom依赖
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency> -
编写配置文件
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--如果需要使用 command的方式生成需要配置数据库驱动的jar包路径 <classPathEntry location="指定数据驱动的磁盘路径"/>--> <!--context 生成上下文 配置生成规则 id 随意写 targetRuntime 生成策略 MyBatis3DynamicSql 默认的,会生成 动态生成sql的方式(没有xml) MyBatis3 生成通用的查询,可以指定动态where条件 MyBatis3Simple 只生成简单的CRUD --> <context id="simple" targetRuntime="MyBatis3"> <commentGenerator> <!--设置是否生成注释 true 不生成 注意: 如果不生成注释,下次生成代码就不会进行合并--> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--数据源 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="root"/> <!--pojo javaModelGenerator java实体生成规则(POJO) targetPackage 生成到哪个包下 targetProject 生成到当前文件的哪个相对路径下 --> <javaModelGenerator targetPackage="com.jiang.pojo" targetProject="src/main/java"/> <!--mapper xml映射文件 sqlMapGenerator mapper xml映射文件生成规则 targetPackage 生成到哪个包下 targetProject 生成到当前文件的哪个相对路径下 --> <sqlMapGenerator targetPackage="com.jiang.mapper" targetProject="src/main/resources"></sqlMapGenerator> <!--mapper接口 javaClientGenerator mapper mapper接口生成规则 type 指定生成的方式 1.使用注解的方式生成 2.使用接口绑定的方式生成(要配置sqlMapGenerator) targetPackage 生成到哪个包下 targetProject 生成到当前文件的哪个相对路径下--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.jiang.mapper" targetProject="src/main/java"/> <!--配置哪些表需要进行代码生成 tableName 表名 domainObjectName pojo类名 mapperName 对应mapper接口的类名 和 mapper xml文件名 --> <table tableName="user" domainObjectName="User" mapperName="UserMapper" /> <table tableName="role" domainObjectName="Role" mapperName="RoleMapper" /> </context> </generatorConfiguration> -
运行
@Test public void test01() throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("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); }
我成功因为我志在成功
浙公网安备 33010602011771号