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> <!-- targetRuntime="MyBatis3Simple":生成简单版的CRUD MyBatis3:豪华版 --> <context id="DB2Tables" targetRuntime="MyBatis3"> <!-- jdbcConnection:指定如何连接到目标数据库 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true" userId="root" password="123456"> </jdbcConnection> <!-- --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- javaModelGenerator:指定javaBean的生成策略 targetPackage="test.model":目标包名 targetProject="MBGTestProjectsrc":目标工程 --> <javaModelGenerator targetPackage="com.atguigu.mybatis.bean" targetProject=".src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- sqlMapGenerator:sql映射生成策略: --> <sqlMapGenerator targetPackage="com.atguigu.mybatis.dao" targetProject=".conf"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- javaClientGenerator:指定mapper接口所在的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mybatis.dao" targetProject=".src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 指定要逆向分析哪些表:根据表要创建javaBean --> <table tableName="tbl_dept" domainObjectName="Department"></table> <table tableName="tbl_employee" domainObjectName="Employee"></table> </context> </generatorConfiguration>
生成文件配置和测验
1 public SqlSessionFactory getSqlSessionFactory() throws IOException { 2 String resource = "mybatis-config.xml"; 3 InputStream inputStream = Resources.getResourceAsStream(resource); 4 return new SqlSessionFactoryBuilder().build(inputStream); 5 } 6 7 @Test 8 public void testMbg() throws Exception { 9 List<String> warnings = new ArrayList<String>(); 10 boolean overwrite = true; 11 File configFile = new File("mbg.xml"); 12 ConfigurationParser cp = new ConfigurationParser(warnings); 13 Configuration config = cp.parseConfiguration(configFile); 14 DefaultShellCallback callback = new DefaultShellCallback(overwrite); 15 MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, 16 callback, warnings); 17 myBatisGenerator.generate(null); 18 } 19 20 @Test 21 public void testMyBatis3Simple() throws IOException{ 22 SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); 23 SqlSession openSession = sqlSessionFactory.openSession(); 24 try{ 25 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); 26 List<Employee> list = mapper.selectByExample(null); 27 for (Employee employee : list) { 28 System.out.println(employee.getId()); 29 } 30 }finally{ 31 openSession.close(); 32 } 33 } 34