欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MyBatis Generator的使用

程序员文章站 2022-04-19 18:42:42
...
  1. 安装MyBatis Generator插件

    下载MyBatis Generator插件插件包解压后将features、plugins文件夹下的架包分别拷贝到eclipse安装目录下的features、plugins文件夹。重启eclipse就行。下载地址: http://download.csdn.net/download/zhong_ling/9875417

  2. 创建generatorConfig.xml文件

    MyBatis Generator的使用配置generatorConfig.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 >
      <!-- 学习地址: http://mbg.cndocs.tk/ -->
      <classPathEntry  location="C:/Users/Window/.m2/repository/mysql/mysql-connector-java/5.1.29/mysql-connector-java-5.1.29.jar" />
      <context id="context1" >
          <!-- 分页插件 -->
        <plugin type="com.uitl.PaginationPlugin" />
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="root" />
        
        <!-- java模型创建器,是必须要的元素  负责:1,key类(见context的defaultModelType);2,java类;
            3,查询类targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制;targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,则生成失败-->
        <javaModelGenerator targetPackage="com.model" targetProject="springMVC_mybaits" />
        
        <!-- 生成mapper.xml文件 -->
        <sqlMapGenerator targetPackage="com.mapping" targetProject="springMVC_mybaits" />
        
        <!-- 生成Mapper接口 -->
        <javaClientGenerator targetPackage="com.dao" targetProject="springMVC_mybaits" type="XMLMAPPER" />
    
        <!-- 选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素 -->
        <table tableName="user" >
          <!-- 指定自增加以及Id  column:字段名, sqlStatement:数据库语句,可以为MySql,DB2,SqlServer,SyBase. identity:true为id,false不为id-->
          <generatedKey column="id" sqlStatement="Mysql"/>
          <!-- 将数据库中的字段重命名为实体类的属性 -->
          <!-- <columnOverride column="id" property="integer" /> -->
        </table>
      </context>
    </generatorConfiguration>
    
  3. 创建好数据库表.
  4. 生成代码(注意指定的目录一定要存在,不然生成不了)右击generatorConfig.xml文件选择Generator MyBatis点击就可以生成代码了MyBatis Generator的使用按上面所述的配置会在dao文件夹下生成UserMapper.java文件在mapping文件夹下面生成UserMapper.xml文件,在model文件夹下面生成UserExample.java和User.java文件.
  5. 以上的配置是生成不了带分页的查询的要自己扩展步骤如下

      引入要用到的jar包,在pom.xml加入下面代码

            <dependency>
    	        <groupId>org.mybatis.generator</groupId>  
    	        <artifactId>mybatis-generator-core</artifactId>  
    	        <version>1.3.2</version>  
    	        <type>jar</type>  
    	        <scope>test</scope>  
            </dependency>
    然后写一个类继承PluginAdapter类,内容如下
    public class PaginationPlugin extends PluginAdapter
    {
    
    	@Override  
        public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,  
                IntrospectedTable introspectedTable) {  
            addLimit(topLevelClass, introspectedTable, "startRow");  
            addLimit(topLevelClass, introspectedTable, "endRow");
            return super.modelExampleClassGenerated(topLevelClass,  
                    introspectedTable);
        }
        @Override  
        public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(  
                XmlElement element, IntrospectedTable introspectedTable) {  
            XmlElement isNotNullElement = new XmlElement("if");  
            isNotNullElement.addAttribute(new Attribute("test", "startRow != null and startRow >= 0")); 
            isNotNullElement.addElement(new TextElement(  
                    "limit #{startRow} , #{endRow}"));  
            element.addElement(isNotNullElement);  
            return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element,  
                    introspectedTable);  
        }
        private void addLimit(TopLevelClass topLevelClass,  
                IntrospectedTable introspectedTable, String name) {  
            CommentGenerator commentGenerator = context.getCommentGenerator();  
            Field field = new Field();
            field.setVisibility(JavaVisibility.PROTECTED);  
            field.setType(PrimitiveTypeWrapper.getIntegerInstance());  
            field.setName(name);  
            commentGenerator.addFieldComment(field, introspectedTable);  
            topLevelClass.addField(field);  
            char c = name.charAt(0);  
            String camel = Character.toUpperCase(c) + name.substring(1);  
            Method method = new Method();  
            method.setVisibility(JavaVisibility.PUBLIC);  
            method.setName("set" + camel);  
            method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name));  
            method.addBodyLine("this." + name + "=" + name + ";");  
            commentGenerator.addGeneralMethodComment(method, introspectedTable);  
            topLevelClass.addMethod(method);  
            method = new Method();  
            method.setVisibility(JavaVisibility.PUBLIC);  
            method.setReturnType(PrimitiveTypeWrapper.getIntegerInstance());  
            method.setName("get" + camel);  
            method.addBodyLine("return " + name + ";");
            commentGenerator.addGeneralMethodComment(method, introspectedTable);  
            topLevelClass.addMethod(method);  
        }
        public boolean validate(List<String> warnings) {  
            return true;  
        }  
    
    
      
    }

    在generatorConfig.xml文件中加入
    <plugin type="插件位置" />
    如上面generatorConfig.xml文件中注释掉的
      	<!-- 分页插件 -->
        <!--<plugin type="com.uitl.PaginationPlugin" /> -->
    再去生成的话就可以生成带分页的代码了.

    以上就是使用的全部内容了.不过感觉生成的内容挺多都重复了所以个人觉得可以把生成后的代码整理一下把公用的部分封装一下.主要是XXXExample.java文件和XXXMapper.java文件.以下是整理后的XXXExample.java
    public class BaseExample {
    	
        protected String orderByClause;
    
        protected boolean distinct;
    
        protected List<Criteria> oredCriteria;
        
        protected Integer startRow;
    
        protected Integer endRow;
    
        public BaseExample() {
            oredCriteria = new ArrayList<Criteria>();
        }
    
        public void setOrderByClause(String orderByClause) {
            this.orderByClause = orderByClause;
        }
    
        public String getOrderByClause() {
            return orderByClause;
        }
    
        public void setDistinct(boolean distinct) {
            this.distinct = distinct;
        }
    
        public boolean isDistinct() {
            return distinct;
        }
    
        public List<Criteria> getOredCriteria() {
            return oredCriteria;
        }
    
        public void or(Criteria criteria) {
            oredCriteria.add(criteria);
        }
    
        public Criteria or() {
            Criteria criteria = createCriteriaInternal();
            oredCriteria.add(criteria);
            return criteria;
        }
    
        public Criteria createCriteria() {
            Criteria criteria = createCriteriaInternal();
            if (oredCriteria.size() == 0) {
                oredCriteria.add(criteria);
            }
            return criteria;
        }
    
        protected Criteria createCriteriaInternal() {
            Criteria criteria = new Criteria();
            return criteria;
        }
    
        public void clear() {
            oredCriteria.clear();
            orderByClause = null;
            distinct = false;
        }
    
        public void setStartRow(Integer startRow) {
            this.startRow=startRow;
        }
    
        public Integer getStartRow() {
            return startRow;
        }
    
        public void setEndRow(Integer endRow) {
            this.endRow=endRow;
        }
    
        public Integer getEndRow() {
            return endRow;
        }
    
        protected abstract static class GeneratedCriteria {
            protected List<Criterion> criteria;
    
            protected GeneratedCriteria() {
                super();
                criteria = new ArrayList<Criterion>();
            }
    
            public boolean isValid() {
                return criteria.size() > 0;
            }
    
            public List<Criterion> getAllCriteria() {
                return criteria;
            }
    
            public List<Criterion> getCriteria() {
                return criteria;
            }
    
            protected void addCriterion(String condition) {
                if (condition == null) {
                    throw new RuntimeException("Value for condition cannot be null");
                }
                criteria.add(new Criterion(condition));
            }
    
            protected void addCriterion(String condition, Object value, String property) {
                if (value == null) {
                    throw new RuntimeException("Value for " + property + " cannot be null");
                }
                criteria.add(new Criterion(condition, value));
            }
    
            protected void addCriterion(String condition, Object value1, Object value2, String property) {
                if (value1 == null || value2 == null) {
                    throw new RuntimeException("Between values for " + property + " cannot be null");
                }
                criteria.add(new Criterion(condition, value1, value2));
            }
    
            
            
            public Criteria andFieldNameIsNull(String fieldName) {
                addCriterion(""+fieldName+" is null");
                return (Criteria) this;
            }
    
            public Criteria andFieldNameIsNotNull(String fieldName) {
                addCriterion(""+fieldName+" is not null");
                return (Criteria) this;
            }
    
            public Criteria andFieldNameEqualTo(Object value,String fieldName) {
                addCriterion(""+fieldName+" =", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameNotEqualTo(Object value,String fieldName) {
                addCriterion(""+fieldName+" <>", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameGreaterThan(Object value,String fieldName) {
                addCriterion(""+fieldName+" >", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameGreaterThanOrEqualTo(Object value,String fieldName) {
                addCriterion(""+fieldName+" >=", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameLessThan(Object value,String fieldName) {
                addCriterion(""+fieldName+" <", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameLessThanOrEqualTo(Object value,String fieldName) {
                addCriterion(""+fieldName+" <=", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameLike(Object value,String fieldName) {
                addCriterion(""+fieldName+" like", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameNotLike(Object value,String fieldName) {
                addCriterion(""+fieldName+" not like", value, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameIn(List<Object> values,String fieldName) {
                addCriterion(""+fieldName+" in", values, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameNotIn(List<Object> values,String fieldName) {
                addCriterion(""+fieldName+" not in", values, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameBetween(Object value1, Object value2,String fieldName) {
                addCriterion(" "+fieldName+" between", value1, value2, fieldName);
                return (Criteria) this;
            }
    
            public Criteria andFieldNameNotBetween(Object value1, Object value2,String fieldName) {
                addCriterion(" "+fieldName+" not between", value1, value2, fieldName);
                return (Criteria) this;
            }
        }
    
        public static class Criteria extends GeneratedCriteria {
    
            protected Criteria() {
                super();
            }
        }
    
        public static class Criterion {
            private String condition;
    
            private Object value;
    
            private Object secondValue;
    
            private boolean noValue;
    
            private boolean singleValue;
    
            private boolean betweenValue;
    
            private boolean listValue;
    
            private String typeHandler;
    
            public String getCondition() {
                return condition;
            }
    
            public Object getValue() {
                return value;
            }
    
            public Object getSecondValue() {
                return secondValue;
            }
    
            public boolean isNoValue() {
                return noValue;
            }
    
            public boolean isSingleValue() {
                return singleValue;
            }
    
            public boolean isBetweenValue() {
                return betweenValue;
            }
    
            public boolean isListValue() {
                return listValue;
            }
    
            public String getTypeHandler() {
                return typeHandler;
            }
    
            protected Criterion(String condition) {
                super();
                this.condition = condition;
                this.typeHandler = null;
                this.noValue = true;
            }
    
            protected Criterion(String condition, Object value, String typeHandler) {
                super();
                this.condition = condition;
                this.value = value;
                this.typeHandler = typeHandler;
                if (value instanceof List<?>) {
                    this.listValue = true;
                } else {
                    this.singleValue = true;
                }
            }
    
            protected Criterion(String condition, Object value) {
                this(condition, value, null);
            }
    
            protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
                super();
                this.condition = condition;
                this.value = value;
                this.secondValue = secondValue;
                this.typeHandler = typeHandler;
                this.betweenValue = true;
            }
    
            protected Criterion(String condition, Object value, Object secondValue) {
                this(condition, value, secondValue, null);
            }
        }
    }

    整理后的XXXMapper.java文件
    public interface BaseMapper<T> {
        /**
         * 统计有多少条数据
         * @param example 条件
         * @return
         */
    	int countByExample(Object example);
    	
    	/**
    	 * 根据条件删除数据
    	 * @param example
    	 * @return
    	 */
        int deleteByExample(Object example);
        
        /**
         *根据ID主键删除数据 
         * @param integer
         * @return
         */
        int deleteByPrimaryKey(Object integer);
    
        /***
         * 保存数据
         * @param record
         * @return
         */
        int insert(Object record);
        /**
         * 插入一条数据,只插入不为null的字段,不会影响有默认值的字段
         * @param record
         * @return
         */
        int insertSelective(Object record);
        
        /**
         * 查询列表
         * @param example
         * @return
         */
        List<T> selectByExample(Object example);
    
        /***
         * 根据主键查询对象
         * @param integer
         * @return
         */
        T selectByPrimaryKey(Object integer);
    
        /**
         * 根据条件修改对象(更新新的model中不为空的字段)
         * @param record
         * @param example
         * @return
         */
        int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);
    
        /**
         * 根据条件修改对象(会将model为空的字段在数据库中置为NULL)
         * @param record
         * @param example
         * @return
         */
        int updateByExample(@Param("record") T record, @Param("example") Object example);
    
        /**
         *根据主键修改对象 (更新新的model中不为空的字段)
         * @param record
         * @return
         */
        int updateByPrimaryKeySelective(T record);
        
        /**
         * 根据主键修改对象(会将model为空的字段在数据库中置为NULL)
         * @param record
         * @return
         */
        int updateByPrimaryKey(T record);
        
    }
    整理后再生成的XXXMapper.java和XXXExample.java可以把里面的内容删除然后继承这两个就好了.

    实例下载地址http://download.csdn.net/download/zhong_ling/9878025  点击下载实例