- mybatis官方提供逆向工程可以针对单表自动生成mybatis执行所需要的代码
- 创建一个generateConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!-- 配置文件内容 (1)如何连接数据库 (2)要生成哪些对象以及如何生成它们 (3)应该使用那些表生成对象 --> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 引入配置文件 --> <properties resource="db.properties"/> <!-- <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip"/>--> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自动生成的注释:true(是),false(否) --> <property name="suppressDate" value="true"/> </commentGenerator> <!-- 数据库的连接信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC类型解析为Integer,为true时,则解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- targetProject:生成Pojo类的位置,路径 targetPackage:生成Pojo类的位置,包 --> <javaModelGenerator targetPackage="cn.muriel.auto.pojo" targetProject="src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="true"/> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="cn.muriel.auto.mapper" targetProject="src"> <!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.muriel.auto.mapper" targetProject="src"> <!-- enableSubPackages:是否让schma作为包的后缀 --> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 指定数据表 --> <table tableName="user"/> <table tableName="food"/> <!-- 有些表的字段需要指定java类型 <table schema="DB2ADMIN" tableName="ALLTYPES" domainObjectName="Customer"> <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>
- 创建一个GenerateorSqlMapUtils工具类
public class GeneratorSqlMapUtils { /** * 基于XML的配置从Java调用MBG * (1)配置文件属性可以作为ConfigurationParser构造函数的参数传递给解析器。如果未显式传递,将搜索JVM系统属性以获取配置文件属性的值。 * 例如,可以使用转义序列$ {generated.source.dir}在配置文件中防伪属性generated.source.dir * (2)如果在配置文件中指定了属性但为解析,则转义的属性字符串将"按原样"传递到生成的代码中 * * @throws Exception */ public void generator() throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; //获取当前类的所在工程路径,必须要在项目根目录 String path = "generatorConfig.xml"; //指定逆向工程配置文件 File configFile = new File(path); 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); } }
- 测试类,自动生成mapper.java、mapper.xml、pojo.java
public static void main(String[] args) { GeneratorSqlMapUtils generatorSqlMapUtils = new GeneratorSqlMapUtils(); try { generatorSqlMapUtils.generator(); } catch (Exception e) { e.printStackTrace(); } }
- 测试类,执行sql语句(全部查询)
public class TestUtil { private static ApplicationContext applicationContext; public static void main(String[] args) { applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper"); JSONArray sendJson = JSONArray.fromObject(userMapper.selectByExample(null)); System.out.println(sendJson + ""); } }
- 测试类,执行sql语句(指定条件查询)
public class TestUtil { private static ApplicationContext applicationContext; public static void main(String[] args) { applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper"); // UserExample userExample = new UserExample(); // UserExample.Criteria criteria = userExample.createCriteria(); // criteria.andUsernameEqualTo("aa"); JSONArray sendJson = JSONArray.fromObject(userMapper.selectByExample(userExample)); System.out.println(sendJson + ""); } }
- 测试类,执行sql语句(更新)
public class TestUtil { private static ApplicationContext applicationContext; public static void main(String[] args) { applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml"); UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper"); User user = new User(); //对所有字段进行更新 userMapper.updateByPrimaryKey(user); //如果传入字段不为空才更新 userMapper.updateByPrimaryKeySelective(user); } }
- 创建一个generateConfig.xml