備忘:mybatis 3的使用記錄

  這是一篇記錄。mybatis是一個部分模仿ORM的framework。是一個介於ORM和原始JDBC的框架。既能夠提供ORM的操做對象的特性,又能從詳細地控制最終的SQL。達到一個平衡。咱們仍是得寫sql,同時mybatis負責類到數據庫記錄的映射。mybatis 3以前叫作ibatis, 2.x時代在apache上。後來移到了別的地方。如今彷佛在http://mybatis.github.io/。 文檔在:http://mybatis.github.io/mybatis-3/,源代碼如今彷佛移到了github:https://github.com/mybatis/。名字也改爲了mybatis。有人開發了一個.net版的mybatis。這個給.net世界帶來了一個很好的思惟。只惋惜目前多數人在關注ORM。java

.net 版mybatis: http://code.google.com/p/mybatisnet/ mysql

mybatis 3有不少改進。在mybatis 3,爲eclipse準備了集成工具。叫作:mybatis generator。這個工具能夠幫咱們省不少事情。git

用下面這個URL來得到mybatis generator。github

http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/sql

  在Eclipse Juno中,Help->Install new software, 在彈出的對話框,Work with對話框中輸入以上URL, 點擊Add,而後輸入這個site的名字。好比輸入mybatis generator。而後等對話框從服務器取到信息,就成了這樣:數據庫

我得說一句,這個工具依賴於maven,因此m2e必定得先裝好。到Eclipse marketplace裏去先裝上maven integration for eclipse Juno or newer。apache

裝好了m2e才能順利裝好mybatis generator。api

好了,勾上那些框,next, next, 贊成,贊成就好了。這樣就把mybatis generator裝好了。服務器

在項目裏用:session

pom.xml文件以下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>mymaven</groupId>
  <artifactId>mymaven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate</artifactId>
          <version>3.5.4-Final</version>
          <type>pom</type>
      </dependency>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-annotations</artifactId>
          <version>3.5.4-Final</version>
      </dependency>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>3.5.4-Final</version>
      </dependency>
      <dependency>
          <groupId>org.javassist</groupId>
          <artifactId>javassist</artifactId>
          <version>3.18.2-GA</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.7</version>
      </dependency>
      <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.1.2</version>
      </dependency>
      <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-core</artifactId>
          <version>1.1.2</version>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.31</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.2.7</version>
      </dependency>
  </dependencies>
  <build>
       <pluginManagement>
          <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
              <version>1.3.1</version>
                  <configuration>  
                      <verbose>true</verbose>  
                      <overwrite>true</overwrite>  
                  </configuration>  
              <executions>
                <execution>
                  <id>Generate MyBatis Artifacts</id>
                  <goals>
                    <goal>generate</goal>
                  </goals>
                </execution>
              </executions>
            </plugin>
         </plugins>
     </pluginManagement>
  </build>
</project>


除此以外還須要一個generatorConfig.xml用來配置mybatis generator:

<?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 >
<!-- 設置mysql驅動路徑 -->
<classPathEntry location="C:\Program Files (x86)\MySQL\Connector J 5.1.29\mysql-connector-java-5.1.29-bin.jar" />
<!-- 此處指定生成針對MyBatis3的DAO -->
  <context id="context1"  targetRuntime="MyBatis3">
  <!-- jdbc鏈接信息 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
    connectionURL="jdbc:mysql://localhost:3306/dbname"
    userId="root" password="xxxxxxxxxxxxxxx" />
    <!-- 生成vo對象 -->
    <javaModelGenerator targetPackage="org.nf.vo" targetProject="src\main\java" />
    <!-- 生成用於查詢的Example對象 -->
    <sqlMapGenerator targetPackage="org.nf.vo" targetProject="src\main\java" />
    <!-- 生成DAO的類文件以及配置文件 -->
    <javaClientGenerator targetPackage="org.nf.dao" targetProject="src\main\java" type="XMLMAPPER" />
    <!-- 想要生成的數據庫表,自動化工具會根據該表的結構生成相應的vo對象 -->
    <table schema="" tableName="Category" >
    </table>
    <table schema="" tableName="Comment" >
    </table>
    <table schema="" tableName="Group" >
    </table>
    <table schema="" tableName="Message" >
    </table>
    <table schema="" tableName="Post" >
    </table>
    <table schema="" tableName="Sensitivekeyword" >
    </table>
    <table schema="" tableName="User" >
    </table>
  </context>
</generatorConfiguration>


這個generatorConfig.xml能夠放到src\main\resources目錄中。這樣,這個資源文件會被mybatis generator找到並解析。這個配置一看就明白。有那麼幾個表,須要用mybatis generator產生代碼。

而後就用maven來產生代碼。右鍵點你的項目,選擇Run as->Run configurations,出來對話框如圖:

若是沒有這個Maven build 配置的化,就新建一個。取個名叫run mybatis generator的配置。而後裏面Goals寫上: mybatis-generator:generate,如圖:

 輸入對了之後就點Run了。後面就是一些maven的log了,能夠看到產生了不少代碼。

[INFO] Scanning for projects...
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.3.1/maven-install-plugin-2.3.1.pom
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.3.1/maven-install-plugin-2.3.1.pom (5 KB at 5.0 KB/sec)
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-site-plugin/3.0/maven-site-plugin-3.0.pom
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-site-plugin/3.0/maven-site-plugin-3.0.pom (20 KB at 24.7 KB/sec)
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-dependency-plugin/2.1/maven-dependency-plugin-2.1.pom
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-dependency-plugin/2.1/maven-dependency-plugin-2.1.pom (8 KB at 20.6 KB/sec)
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-dependency-plugin/2.1/maven-dependency-plugin-2.1.jar
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-dependency-plugin/2.1/maven-dependency-plugin-2.1.jar (104 KB at 60.2 KB/sec)
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-release-plugin/2.0/maven-release-plugin-2.0.pom
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-release-plugin/2.0/maven-release-plugin-2.0.pom (8 KB at 20.7 KB/sec)
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/release/maven-release/2.0/maven-release-2.0.pom
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/release/maven-release/2.0/maven-release-2.0.pom (7 KB at 12.1 KB/sec)
Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-release-plugin/2.0/maven-release-plugin-2.0.jar
Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-release-plugin/2.0/maven-release-plugin-2.0.jar (38 KB at 48.3 KB/sec)
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building mymaven 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- mybatis-generator-maven-plugin:1.3.1:generate (default-cli) @ mymaven ---
[INFO] Connecting to the Database
[INFO] Introspecting table Category
[INFO] Introspecting table Comment
[INFO] Introspecting table Group
[INFO] Introspecting table Message
[INFO] Introspecting table Post
[INFO] Introspecting table Sensitivekeyword
[INFO] Introspecting table User
[INFO] Generating Example class for table category
[INFO] Generating Record class for table category
[INFO] Generating Mapper Interface for table category
[INFO] Generating SQL Map for table category
[INFO] Generating Example class for table comment
[INFO] Generating Record class for table comment
[INFO] Generating Mapper Interface for table comment
[INFO] Generating SQL Map for table comment
[INFO] Generating Example class for table group
[INFO] Generating Record class for table group
[INFO] Generating Mapper Interface for table group
[INFO] Generating SQL Map for table group
[INFO] Generating Example class for table message
[INFO] Generating Record class for table message
[INFO] Generating Mapper Interface for table message
[INFO] Generating SQL Map for table message
[INFO] Generating Example class for table post
[INFO] Generating Record class for table post
[INFO] Generating Mapper Interface for table post
[INFO] Generating SQL Map for table post
[INFO] Generating Example class for table sensitivekeyword
[INFO] Generating Record class for table sensitivekeyword
[INFO] Generating Mapper Interface for table sensitivekeyword
[INFO] Generating SQL Map for table sensitivekeyword
[INFO] Generating Example class for table user
[INFO] Generating Record class for table user
[INFO] Generating Mapper Interface for table user
[INFO] Generating SQL Map for table user
[INFO] Saving file CategoryMapper.xml
[INFO] Saving file CommentMapper.xml
[INFO] Saving file GroupMapper.xml
[INFO] Saving file MessageMapper.xml
[INFO] Saving file PostMapper.xml
[INFO] Saving file SensitivekeywordMapper.xml
[INFO] Saving file UserMapper.xml
[INFO] Saving file CategoryExample.java
[INFO] Saving file Category.java
[INFO] Saving file CategoryMapper.java
[INFO] Saving file CommentExample.java
[INFO] Saving file Comment.java
[INFO] Saving file CommentMapper.java
[INFO] Saving file GroupExample.java
[INFO] Saving file Group.java
[INFO] Saving file GroupMapper.java
[INFO] Saving file MessageExample.java
[INFO] Saving file Message.java
[INFO] Saving file MessageMapper.java
[INFO] Saving file PostExample.java
[INFO] Saving file Post.java
[INFO] Saving file PostMapper.java
[INFO] Saving file SensitivekeywordExample.java
[INFO] Saving file Sensitivekeyword.java
[INFO] Saving file SensitivekeywordMapper.java
[INFO] Saving file UserExample.java
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 10.614s
[INFO] Finished at: Sun Jul 13 22:47:25 CST 2014
[INFO] Final Memory: 9M/123M
[INFO] ------------------------------------------------------------------------

按照以前generatorConfig.xml的配置,dao類都會在org.nf.dao目錄中。virtual object就都在org.nf.vo目錄中。
查看一下generator爲咱們產生的代碼。發現它產生的代碼還挺全面的。

例如咱們的model類

package org.nf.vo;

public class Category {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column category.CategoryId
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    private Integer categoryid;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column category.CategoryName
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    private String categoryname;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column category.ParentCategoryId
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    private Integer parentcategoryid;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column category.ShortName
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    private String shortname;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column category.CategoryId
     *
     * @return the value of category.CategoryId
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public Integer getCategoryid() {
        return categoryid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column category.CategoryId
     *
     * @param categoryid the value for category.CategoryId
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void setCategoryid(Integer categoryid) {
        this.categoryid = categoryid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column category.CategoryName
     *
     * @return the value of category.CategoryName
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public String getCategoryname() {
        return categoryname;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column category.CategoryName
     *
     * @param categoryname the value for category.CategoryName
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void setCategoryname(String categoryname) {
        this.categoryname = categoryname;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column category.ParentCategoryId
     *
     * @return the value of category.ParentCategoryId
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public Integer getParentcategoryid() {
        return parentcategoryid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column category.ParentCategoryId
     *
     * @param parentcategoryid the value for category.ParentCategoryId
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void setParentcategoryid(Integer parentcategoryid) {
        this.parentcategoryid = parentcategoryid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column category.ShortName
     *
     * @return the value of category.ShortName
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public String getShortname() {
        return shortname;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column category.ShortName
     *
     * @param shortname the value for category.ShortName
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void setShortname(String shortname) {
        this.shortname = shortname;
    }
}

這個類映射數據庫裏的Category表。

這沒有多少。無非就是一些fields加get和set方法。仍是CategoryExample類的內容多一些。

package org.nf.vo;

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

public class CategoryExample {
    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    protected String orderByClause;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    protected boolean distinct;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    protected List<Criteria> oredCriteria;

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public CategoryExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public String getOrderByClause() {
        return orderByClause;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public boolean isDistinct() {
        return distinct;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    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 andCategoryidIsNull() {
            addCriterion("CategoryId is null");
            return (Criteria) this;
        }

        public Criteria andCategoryidIsNotNull() {
            addCriterion("CategoryId is not null");
            return (Criteria) this;
        }

        public Criteria andCategoryidEqualTo(Integer value) {
            addCriterion("CategoryId =", value, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidNotEqualTo(Integer value) {
            addCriterion("CategoryId <>", value, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidGreaterThan(Integer value) {
            addCriterion("CategoryId >", value, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidGreaterThanOrEqualTo(Integer value) {
            addCriterion("CategoryId >=", value, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidLessThan(Integer value) {
            addCriterion("CategoryId <", value, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidLessThanOrEqualTo(Integer value) {
            addCriterion("CategoryId <=", value, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidIn(List<Integer> values) {
            addCriterion("CategoryId in", values, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidNotIn(List<Integer> values) {
            addCriterion("CategoryId not in", values, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidBetween(Integer value1, Integer value2) {
            addCriterion("CategoryId between", value1, value2, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategoryidNotBetween(Integer value1, Integer value2) {
            addCriterion("CategoryId not between", value1, value2, "categoryid");
            return (Criteria) this;
        }

        public Criteria andCategorynameIsNull() {
            addCriterion("CategoryName is null");
            return (Criteria) this;
        }

        public Criteria andCategorynameIsNotNull() {
            addCriterion("CategoryName is not null");
            return (Criteria) this;
        }

        public Criteria andCategorynameEqualTo(String value) {
            addCriterion("CategoryName =", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameNotEqualTo(String value) {
            addCriterion("CategoryName <>", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameGreaterThan(String value) {
            addCriterion("CategoryName >", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameGreaterThanOrEqualTo(String value) {
            addCriterion("CategoryName >=", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameLessThan(String value) {
            addCriterion("CategoryName <", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameLessThanOrEqualTo(String value) {
            addCriterion("CategoryName <=", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameLike(String value) {
            addCriterion("CategoryName like", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameNotLike(String value) {
            addCriterion("CategoryName not like", value, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameIn(List<String> values) {
            addCriterion("CategoryName in", values, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameNotIn(List<String> values) {
            addCriterion("CategoryName not in", values, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameBetween(String value1, String value2) {
            addCriterion("CategoryName between", value1, value2, "categoryname");
            return (Criteria) this;
        }

        public Criteria andCategorynameNotBetween(String value1, String value2) {
            addCriterion("CategoryName not between", value1, value2, "categoryname");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidIsNull() {
            addCriterion("ParentCategoryId is null");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidIsNotNull() {
            addCriterion("ParentCategoryId is not null");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidEqualTo(Integer value) {
            addCriterion("ParentCategoryId =", value, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidNotEqualTo(Integer value) {
            addCriterion("ParentCategoryId <>", value, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidGreaterThan(Integer value) {
            addCriterion("ParentCategoryId >", value, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidGreaterThanOrEqualTo(Integer value) {
            addCriterion("ParentCategoryId >=", value, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidLessThan(Integer value) {
            addCriterion("ParentCategoryId <", value, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidLessThanOrEqualTo(Integer value) {
            addCriterion("ParentCategoryId <=", value, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidIn(List<Integer> values) {
            addCriterion("ParentCategoryId in", values, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidNotIn(List<Integer> values) {
            addCriterion("ParentCategoryId not in", values, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidBetween(Integer value1, Integer value2) {
            addCriterion("ParentCategoryId between", value1, value2, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andParentcategoryidNotBetween(Integer value1, Integer value2) {
            addCriterion("ParentCategoryId not between", value1, value2, "parentcategoryid");
            return (Criteria) this;
        }

        public Criteria andShortnameIsNull() {
            addCriterion("ShortName is null");
            return (Criteria) this;
        }

        public Criteria andShortnameIsNotNull() {
            addCriterion("ShortName is not null");
            return (Criteria) this;
        }

        public Criteria andShortnameEqualTo(String value) {
            addCriterion("ShortName =", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameNotEqualTo(String value) {
            addCriterion("ShortName <>", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameGreaterThan(String value) {
            addCriterion("ShortName >", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameGreaterThanOrEqualTo(String value) {
            addCriterion("ShortName >=", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameLessThan(String value) {
            addCriterion("ShortName <", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameLessThanOrEqualTo(String value) {
            addCriterion("ShortName <=", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameLike(String value) {
            addCriterion("ShortName like", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameNotLike(String value) {
            addCriterion("ShortName not like", value, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameIn(List<String> values) {
            addCriterion("ShortName in", values, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameNotIn(List<String> values) {
            addCriterion("ShortName not in", values, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameBetween(String value1, String value2) {
            addCriterion("ShortName between", value1, value2, "shortname");
            return (Criteria) this;
        }

        public Criteria andShortnameNotBetween(String value1, String value2) {
            addCriterion("ShortName not between", value1, value2, "shortname");
            return (Criteria) this;
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table category
     *
     * @mbggenerated do_not_delete_during_merge Sun Jul 13 22:47:25 CST 2014
     */
    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    /**
     * This class was generated by MyBatis Generator.
     * This class corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    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);
        }
    }
}

這個CategoryExample給咱們一個很好的寫條件表達式的例子。對於integer類型的字段,有諸如greaterthan, lessthan之類的方法。而串類型的字段,就有like 這樣的方法。而後不一樣的條件之間能夠用and和or關係。這個給咱們查詢某些特殊條件的數據是帶來的方便。

以後兩個能夠說是關鍵部分,一個是Mapper接口和Mapper的xml定義。一個定義了這個model類有什麼方法能夠調用,另外一個定義了這些方法的實現方式。

這是Mapper接口:

package org.nf.dao;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.nf.vo.Category;
import org.nf.vo.CategoryExample;

public interface CategoryMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int countByExample(CategoryExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int deleteByExample(CategoryExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int deleteByPrimaryKey(Integer categoryid);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int insert(Category record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int insertSelective(Category record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    List<Category> selectByExample(CategoryExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    Category selectByPrimaryKey(Integer categoryid);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int updateByExampleSelective(@Param("record") Category record, @Param("example") CategoryExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int updateByExample(@Param("record") Category record, @Param("example") CategoryExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int updateByPrimaryKeySelective(Category record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table category
     *
     * @mbggenerated Sun Jul 13 22:47:25 CST 2014
     */
    int updateByPrimaryKey(Category record);
}

 

這是CategoryMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.nf.dao.CategoryMapper" >
  <resultMap id="BaseResultMap" type="org.nf.vo.Category" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    <id column="CategoryId" property="categoryid" jdbcType="INTEGER" />
    <result column="CategoryName" property="categoryname" jdbcType="VARCHAR" />
    <result column="ParentCategoryId" property="parentcategoryid" jdbcType="INTEGER" />
    <result column="ShortName" property="shortname" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    CategoryId, CategoryName, ParentCategoryId, ShortName
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="org.nf.vo.CategoryExample" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from category
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    select 
    <include refid="Base_Column_List" />
    from category
    where CategoryId = #{categoryid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    delete from category
    where CategoryId = #{categoryid,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="org.nf.vo.CategoryExample" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    delete from category
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="org.nf.vo.Category" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    insert into category (CategoryId, CategoryName, ParentCategoryId, 
      ShortName)
    values (#{categoryid,jdbcType=INTEGER}, #{categoryname,jdbcType=VARCHAR}, #{parentcategoryid,jdbcType=INTEGER}, 
      #{shortname,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="org.nf.vo.Category" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    insert into category
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="categoryid != null" >
        CategoryId,
      </if>
      <if test="categoryname != null" >
        CategoryName,
      </if>
      <if test="parentcategoryid != null" >
        ParentCategoryId,
      </if>
      <if test="shortname != null" >
        ShortName,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="categoryid != null" >
        #{categoryid,jdbcType=INTEGER},
      </if>
      <if test="categoryname != null" >
        #{categoryname,jdbcType=VARCHAR},
      </if>
      <if test="parentcategoryid != null" >
        #{parentcategoryid,jdbcType=INTEGER},
      </if>
      <if test="shortname != null" >
        #{shortname,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="org.nf.vo.CategoryExample" resultType="java.lang.Integer" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    select count(*) from category
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    update category
    <set >
      <if test="record.categoryid != null" >
        CategoryId = #{record.categoryid,jdbcType=INTEGER},
      </if>
      <if test="record.categoryname != null" >
        CategoryName = #{record.categoryname,jdbcType=VARCHAR},
      </if>
      <if test="record.parentcategoryid != null" >
        ParentCategoryId = #{record.parentcategoryid,jdbcType=INTEGER},
      </if>
      <if test="record.shortname != null" >
        ShortName = #{record.shortname,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    update category
    set CategoryId = #{record.categoryid,jdbcType=INTEGER},
      CategoryName = #{record.categoryname,jdbcType=VARCHAR},
      ParentCategoryId = #{record.parentcategoryid,jdbcType=INTEGER},
      ShortName = #{record.shortname,jdbcType=VARCHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="org.nf.vo.Category" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    update category
    <set >
      <if test="categoryname != null" >
        CategoryName = #{categoryname,jdbcType=VARCHAR},
      </if>
      <if test="parentcategoryid != null" >
        ParentCategoryId = #{parentcategoryid,jdbcType=INTEGER},
      </if>
      <if test="shortname != null" >
        ShortName = #{shortname,jdbcType=VARCHAR},
      </if>
    </set>
    where CategoryId = #{categoryid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="org.nf.vo.Category" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Sun Jul 13 22:47:25 CST 2014.
    -->
    update category
    set CategoryName = #{categoryname,jdbcType=VARCHAR},
      ParentCategoryId = #{parentcategoryid,jdbcType=INTEGER},
      ShortName = #{shortname,jdbcType=VARCHAR}
    where CategoryId = #{categoryid,jdbcType=INTEGER}
  </update>
</mapper>

這個CategoryMapper定義了一些CRUD方法的實現方式。好比updateByPrimaryKeySelective就能根據輸入的參數來決定更新哪些字段。同時咱們還能夠在其參數CategoryExample中傳入若干個條件。好比id大於一個數值,name中包含某某字符等等條件。那麼更新哪些記錄就能夠本身定義條件了。這是一個很大的進步。很方便。

把Mapper xml放到src/main/resources目錄下,這樣這些xml就會打包到發佈的jar包裏。

試着調用這些產生的代碼:

package org.nf;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.nf.model.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class myfirst {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    /**
     * @param args
     */
    public static void main(String[] args) {
        
    //mybatis
        try{
            reader    =  Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
        SqlSession sessionmybatis = sqlSessionFactory.openSession();
        try {
            org.nf.vo.Category categorymybatis = (org.nf.vo.Category) sessionmybatis.selectOne("org.nf.dao.CategoryMapper.selectByPrimaryKey", 5);
            System.out.println(categorymybatis.getCategoryname());
        } finally {
            sessionmybatis.close();
        }
        logger.info("End");
    }

}
相關文章
相關標籤/搜索