mybatis逆向工程

mybatis逆向工程 (MyBatis Generator)

什么是mybatis的逆向工程

mybatis官方为了提高效率,通过单表自动生成sql,包括mapper.xml,mapper.java,表名.java(po类)



在企业开发中通常是在设计阶段对表进行设计 、创建。
在开发阶段根据表结构创建对应的po类。
mybatis逆向工程的方向:由数据库表生成java代码

逆向工程 使用配置

XML配置

1、连接数据库的地址和驱动
    <jdbcConnection 
        driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/mybatis"
        userId="root"
        password="mysql">
    </jdbcConnection>
2、需要配置po类的包路径
    <!-- targetProject:生成PO类的位置 -->
    <javaModelGenerator targetPackage="cn.itcast.mybatis.po"
        targetProject=".\src">
        <!-- enableSubPackages:是否让schema作为包的后缀 -->
        <property name="enableSubPackages" value="false" />
        <!-- 从数据库返回的值被清理前后的空格 -->
        <property name="trimStrings" value="true" />
    </javaModelGenerator>
3、需要配置mapper包的路径
    <!-- targetProject:mapper映射文件生成的位置 -->
    <sqlMapGenerator targetPackage="cn.itcast.mybatis.mapper" 
        targetProject=".\src">
        <!-- enableSubPackages:是否让schema作为包的后缀 -->
        <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>
    <!-- targetPackage:mapper接口生成的位置 -->
    <javaClientGenerator type="XMLMAPPER"
        targetPackage="cn.itcast.mybatis.mapper" 
        targetProject=".\src">
        <!-- enableSubPackages:是否让schema作为包的后缀 -->
        <property name="enableSubPackages" value="false" />
    </javaClientGenerator>
4、指定数据表
    <!-- 指定数据库表 -->
    <table tableName="items"></table>
    <table tableName="orders"></table>
    <table tableName="orderdetail"></table>

java程序

通过java程序生成mapper类、po类...
public class GeneratorSqlmap {

public void generator() 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);

} 
public static void main(String[] args) throws Exception {
    try {
        GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
        generatorSqlmap.generator();
    } catch (Exception e) {
        e.printStackTrace();
    }
    
}

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容