详解在springboot中使用Mybatis Generator的两种方式

介绍

Mybatis Generator(MBG)是Mybatis的一个代码生成工具。MBG解决了对数据库操作有最大影响的一些CRUD操作,很大程度上提升开发效率。如果需要联合查询仍然需要手写sql。相信很多人都听说过微服务,各个微服务之间是松耦合的。每个微服务仅关注于完成一件任务并很好地完成该任务。在一个微服务的开发过程中很可能只关注对单表的操作。所以MBG在开发过程中可以快速的生成代码提升开发效率。

本文将说到在springboot的项目中如何去配置(XML形式和Java配置类形式)和使用MBG以及MBG生成代码的两种方式(XML形式和注解形式),在springboot中更推荐去使用注解的形式。

MBG配置

1.添加依赖

  
    org.mybatis.generator
    mybatis-generator-core
    1.3.5
  

2.XML配置

配置示例:在新建springboot项目的根目录下创建mbg.xml文件。


    

  
    
       
      
      
      
      
    
    
     
   
      
    
      
    
    
    
    
     
     
    
  
  
    
     
    
  
    
    
     
     
     
    
      
      
    

配置详解






 


 

  
  
  
  
  
  
  
  

  
  
  

  
  
    
  

  
  
    
    
  

  
  
    
    

    
    

    
    

    
    

    
    
  

  
  
    
    
  

  
  
    
    
    
  
  
  

    
    

    
    

    
    

    

    

    

    

    
    
    

    
    

    

    

     
        
      

     
       
       

       

       

       

       
     

     
  

生成代码:

public class TestMGB {
  public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
    List warnings =new ArrayList();
    boolean overwrite=true;
    File configFile=new File("mgb.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.Java配置示例

基于Java的配置是和上面的XML配置是相对应的。直接运行该示例即可生成数据表对于的pojo,mapper接口和一个sqlprovider Java类。

package com.mgb.test;

import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.CommentGeneratorConfiguration;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.JDBCConnectionConfiguration;
import org.mybatis.generator.config.JavaClientGeneratorConfiguration;
import org.mybatis.generator.config.JavaModelGeneratorConfiguration;
import org.mybatis.generator.config.JavaTypeResolverConfiguration;
import org.mybatis.generator.config.ModelType;
import org.mybatis.generator.config.PluginConfiguration;
import org.mybatis.generator.config.SqlMapGeneratorConfiguration;
import org.mybatis.generator.config.TableConfiguration;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MGBConfig {
  public static void main(String[] args) throws Exception{
     //配置xml配置项
     List warnings = new ArrayList();
     boolean overwrite = true;
     Configuration config = new Configuration();
     Context context = new Context(ModelType.CONDITIONAL);
     context.setTargetRuntime("MyBatis3");
     context.setId("defaultContext");
     
    //自动识别数据库关键字,默认false,如果设置为true,
    //根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),
    //使用columnOverride覆盖
     context.addProperty("autoDelimitKeywords","true");
     
    //生成的Java文件的编码
    context.addProperty("javaFileEncoding","utf-8");
    context.addProperty("beginningDelimiter","`");
    context.addProperty("endingDelimiter","`");
    //格式化java代码
    context.addProperty("javaFormatter","org.mybatis.generator.api.dom.DefaultJavaFormatter");
    //格式化xml代码
    context.addProperty("xmlFormatter","org.mybatis.generator.api.dom.DefaultXmlFormatter");
    //格式化信息
    PluginConfiguration pluginConfiguration = new PluginConfiguration();
    pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.SerializablePlugin");
    pluginConfiguration.setConfigurationType("org.mybatis.generator.plugins.ToStringPlugin");
    context.addPluginConfiguration(pluginConfiguration);
    
    //设置是否去除生成注释
    CommentGeneratorConfiguration commentGeneratorConfiguration = new CommentGeneratorConfiguration();
    commentGeneratorConfiguration.addProperty("suppressAllComments","true");
    //commentGeneratorConfiguration.addProperty("suppressDate","true");
    context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);
  
    //设置连接数据库
    JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
    jdbcConnectionConfiguration.setDriverClass("com.mysql.jdbc.Driver");
    jdbcConnectionConfiguration.setConnectionURL("jdbc:mysql://localhost:3306/definesys");
    jdbcConnectionConfiguration.setPassword("welcome1");
    jdbcConnectionConfiguration.setUserId("root");
    context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
    
    JavaTypeResolverConfiguration javaTypeResolverConfiguration = new JavaTypeResolverConfiguration();
    //是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.)
    javaTypeResolverConfiguration.addProperty("forceBigDecimals","false");
    context.setJavaTypeResolverConfiguration(javaTypeResolverConfiguration);
    
    //生成实体类的地址
    JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
    javaModelGeneratorConfiguration.setTargetPackage("com.mgb.domain");
    javaModelGeneratorConfiguration.setTargetProject("src/main/java");
    javaModelGeneratorConfiguration.addProperty("enableSubPackages","true");
    javaModelGeneratorConfiguration.addProperty("trimStrings","true");
    context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
    
    //生成的xml的地址
    SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
    sqlMapGeneratorConfiguration.setTargetProject("src/main/java");
    sqlMapGeneratorConfiguration.setTargetPackage("com.mgb.mapper");
    sqlMapGeneratorConfiguration.addProperty("enableSubPackages","true");
    context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
    
    //生成注解接口
    JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
    javaClientGeneratorConfiguration.setTargetPackage("com.mgb.dao");
    javaClientGeneratorConfiguration.setTargetProject("src/main/java");
    //注解形式 ANNOTATEDMAPPER xml形式 XMLMAPPER
    javaClientGeneratorConfiguration.setConfigurationType("ANNOTATEDMAPPER");
    javaClientGeneratorConfiguration.addProperty("enableSubPackages","true");
    context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
    
    TableConfiguration tableConfiguration = new TableConfiguration(context);
    tableConfiguration.setTableName("user_info");
    tableConfiguration.setCountByExampleStatementEnabled(true);
    tableConfiguration.setUpdateByExampleStatementEnabled(true);
    tableConfiguration.setDeleteByExampleStatementEnabled(true);
    tableConfiguration.setInsertStatementEnabled(true);
    tableConfiguration.setDeleteByPrimaryKeyStatementEnabled(true);    
    context.addTableConfiguration(tableConfiguration);
    
    config.addContext(context);
    DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    myBatisGenerator.generate(null);
  }  
}

使用

package com.mgb.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mgb.dao.UserInfoMapper;
import com.mgb.domain.UserInfo;
import com.mgb.domain.UserInfoExample;

@Service
public class UserService {
  @Autowired
  private UserInfoMapper userInfoMapper;
  
  /**
   * 按姓名查询
   * @param name
   * @return
   */
  public List getUserByName(String name){
    UserInfoExample uerInfoExample=new UserInfoExample();
    uerInfoExample.createCriteria().andNameEqualTo(name);
    return userInfoMapper.selectByExample(uerInfoExample);
  }
  
  /**
   * 有条件的insert
   * @param userInfo
   * @return
   */
  public Integer addUser(UserInfo userInfo) {
    return userInfoMapper.insertSelective(userInfo);
  }
  
  /**
   * 根据ID更新用户信息
   * @param userInfo
   * @return
   */
  public Integer updateUser(UserInfo userInfo) {
    return userInfoMapper.updateByPrimaryKey(userInfo);
  }
  
  /**
   * 根据ID删除用户
   * @param id
   * @return
   */
  public Integer deleteUserById(Integer id) {
    return userInfoMapper.deleteByPrimaryKey(id);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(详解在springboot中使用Mybatis Generator的两种方式)