Mybatis Generator(MBG)通过丰富的配置可以生成不同类型的代码,代码包含了数据库表对应的实体类,Mapper接口类,Mapper XML文件和Example对象等。这些代码文件中几乎包含了全部的单表操作方法,使用MBG可以极大程度上方便我们使用Mybatis。
接下来介绍具体的配置过程:
1、配置 mbg.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> <!--jdbcConnection:指定如何连接到目标数据库 targetRuntime="MyBatis3Simple":生成简单版的CRUD targetRuntime="MyBatis3":生成复杂的CRUD --> <context id="DB2Tables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="13579"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--javaModelGenerator:指定Javabean的生成策略 targetPackage ="test.model" 目标包名 argetProject = "\ MBGTestProject \ src" 目标工程 --> <javaModelGenerator targetPackage ="com.lhk.mybatis.bean" targetProject = ".\src"> <property name ="enableSubPackages" value ="true"/> <property name ="trimStrings" value = "true"/> </javaModelGenerator> <!--sqlMapGenerator:sql映射生成策略 targetPackage ="test.xml" 目标包名 targetProject ="\MBGTestProject\ src" 目标工程 --> <sqlMapGenerator targetPackage ="conf" targetProject =".\src"> <property name ="enableSubPackages" value ="true"/> </sqlMapGenerator> <!--javaClientGenerator:指定mapper接口所在的位置 targetPackage = "test.dao" 目标包名 targetProject = "\ MBGTestProject \ src" 目标工程 --> <javaClientGenerator type = "XMLMAPPER" targetPackage = "com.lhk.mybatis.dao" targetProject = ".\src"> <property name ="enableSubPackages" value ="true"/> </javaClientGenerator> <!--table:指定要逆向生成的表,根据表要创建Javabean tableName ="tb1_employee" 数据库中的表名 domainObjectName ="Employee" 对应生成的Javabean类名称 --> <table tableName ="tb1_employee" domainObjectName ="Employee"> <property name="useActualColumnNames" value="true"/> <generatedKey column="ID" sqlStatement="DB2" identity="true" /> <columnOverride column="DATE_FIELD" property="startDate" /> <ignoreColumn column="FRED" /> <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> </table> <table tableName="tb1_dept" domainObjectName="Department"> <property name="useActualColumnNames" value="true"/> <generatedKey column="ID" sqlStatement="DB2" identity="true" /> <columnOverride column="DATE_FIELD" property="startDate" /> <ignoreColumn column="FRED" /> <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> </table> </context> </generatorConfiguration>
2、添加 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 数据库连接的配置信息 驱动,URL,用户名,密码--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis" /> <property name="username" value="root" /> <property name="password" value="13579" /> </dataSource> </environment> </environments> <!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 --> <mappers> <mapper resource="conf/EmployeeMapper.xml" /> <mapper resource="conf/DepartmentMapper.xml" /> </mappers> </configuration>
3、添加MyBatisTest测试类
用于执行MBG配置生成代码
@Test public void testMbg() throws Exception{ //MBG执行过程中的警告信息 List<String> warnings = new ArrayList<>(); //当生成代码重复时,覆盖原代码 boolean overwrite = true; //读取MBG配置文件 File configFile = new File("E:\\java\\IDEATest\\Mybatis_MBG\\src\\conf\\mbg.xml"); // ...根据需要填写配置对象...... ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); // 创建MBG MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,callback,warnings); // 执行生成代码 myBatisGenerator.generate(null); }
在通过MBG生成代码之前,项目的结构为:
在使用MBG生成代码后,项目的结构为:
可以看到通过MBG自动生成了实体类,Mapper接口类,Mapper XML文件和Example对象。
4、测试自动生成的查询方法
public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "conf/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testSimple() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try { EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); //查询员工名字中有e字母的,和员工性别是0的 //封装员工查询条件example EmployeeExample example = new EmployeeExample(); //创建一个Criteria,这个Criteria就是拼装查询条件 EmployeeExample.Criteria criteria = example.createCriteria(); criteria.andLast_nameLike("%e%"); criteria.andGenderEqualTo("0"); //添加or查询,新建一个Criteria,然后example.or(criteria2) EmployeeExample.Criteria criteria2 = example.createCriteria(); criteria2.andEmailLike("%e%"); example.or(criteria2); List<Employee> selectList = mapper.selectByExample(example); for (Employee employee : selectList) { System.out.println(employee.getId()); } } finally { openSession.close(); } }