首页 > 代码库 > 备忘:mybatis 3的使用记录
备忘: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。
.net 版mybatis: http://code.google.com/p/mybatisnet/
mybatis 3有很多改进。在mybatis 3,为eclipse准备了集成工具。叫做:mybatis generator。这个工具可以帮我们省很多事情。
用下面这个URL来获得mybatis generator。
http://mybatis.googlecode.com/svn/sub-projects/generator/trunk/eclipse/UpdateSite/
在Eclipse Juno中,Help->Install new software, 在弹出的对话框,Work with对话框中输入以上URL, 点击Add,然后输入这个site的名字。比如输入mybatis generator。然后等对话框从服务器取到信息,就成了这样:
我得说一句,这个工具依赖于maven,所以m2e一定得先装好。到Eclipse marketplace里去先装上maven integration for eclipse Juno or newer。
装好了m2e才能顺利装好mybatis generator。
好了,勾上那些框,next, next, 同意,同意就行了。这样就把mybatis generator装好了。
在项目里用:
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.pomDownloaded: 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.pomDownloaded: 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.pomDownloaded: 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.jarDownloaded: 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.pomDownloaded: 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.pomDownloaded: 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.jarDownloaded: 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 =http://www.mamicode.com/= 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 = http://www.mamicode.com/true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value =http://www.mamicode.com/ value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = http://www.mamicode.com/true; } else { this.singleValue = http://www.mamicode.com/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 =http://www.mamicode.com/ value; this.secondValue =http://www.mamicode.com/ secondValue; this.typeHandler = typeHandler; this.betweenValue = http://www.mamicode.com/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"); }}
备忘:mybatis 3的使用记录