1.逆向工程简介
MyBatis Generator: 简称MBG,是一个专门为MyBatis框架使用者定制的代码生成器,可以快速的根据表生成对应的映射文件,接口,以及bean类。支持基本的增删改查,以及QBC风格的条件查询。但是表连接、存储过程等这些复杂sql的定义需要我们手工编写
官方文档地址:
http://www.mybatis.org/generator/
官方工程地址:
https://github.com/mybatis/generator/releases
2.逆向工程的配置
2.1导入逆向工程的jar包
maven仓库地址:https://mvnrepository.com/
在maven仓库网站中搜mybatis-generator-core
这里以1.3.6为例,复制到pom.xml导入包
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.6</version> </dependency>
|
2.2配置时注意一些必须属性
自己在配置的时候要不要忘了一些必须属性,如:数据库表名
2.3编写MBG的配置文件mbg.xml(重要几处配置),参考官方文档
注意:如果使用的是MySQL8,在jdbcConnection标签中还需要添加以下标签<property name=”nullCatalogMeansCurrent” value=true” />
<!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="simple" targetRuntime="MyBatis3Simple"> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="root"/>
<javaModelGenerator targetPackage="com.atguigu.mybatis.mbg.beans" targetProject="src"/>
<sqlMapGenerator targetPackage="com.atguigu.mybatis.mbg.mapper" targetProject="src"/>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mybatis.mbg.mapper" targetProject="src"/>
<table tableName="employees" domainObjectName="Employee"/> <table tableName="departments" domainObjectName="Department"/> </context> </generatorConfiguration>
|
2.4参考官方文档创建代码生成器运行代码
@Test public void testMGB() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("mbg.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); }
|
3.逆向工程的使用
参考Mybatis官方文档:
https://mybatis.org/mybatis-3/zh/getting-started.html
3.1从 XML 中构建 SqlSessionFactory
3.2从 SqlSessionFactory 中获取 SqlSession
3.3完整的基本查询测试代码
@Test public void testSelectByPrimaryKey() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = mapper.selectByPrimaryKey(1); System.out.println(employee); } finally { sqlSession.close(); } }
|
4.补充
具体的配置可以看Mybatis中的教程,想用带条件的SQL则在xml文件里改一下targetRuntime属性值说明(之前用的是MyBatis3Simple)
