1. 程式人生 > 實用技巧 >Mybatis之逆向工程的檔案和方法解析

Mybatis之逆向工程的檔案和方法解析

一、Mybatis逆向工程生成的檔案:

BlogMapper.xml : mapper對映檔案
BlogMapper.java:mapper介面檔案
Blog.java:實體類
BlogExample.java:實體類對應的example。用於新增條件,相當於where後面的部分。
BlogWithBLOBs.java:繼承了實體類Blog。同時在BlogMapper.xml中繼承了BaseResultMap,有自己特殊的欄位,對應資料表的text、longvarchar等長型別,如果資料庫沒有長資料型別則不會生成該檔案。

檢索大欄位時,則需要使用selectByExampleWithBLOBs ,一般情況則使用selectByExample 即可。

二、BlogExample.java 和 BlogWithBLOBs.java的區別:

進行逆向工程的資料表如下,可以看出該表包含了text和longtext型別。


逆向生成的Blog和BlogWithBLOBs 實體類,BlogWithBLOBs繼承了Blog類,可以看出text和longtext這兩個長型別是單獨在BlogWithBLOBs類中實現的。

//Blog.java的程式碼
package com.online.domain;
public class Blog {
    private Integer id;
    private String title;
    private String summary;
    //省略get和set方法
}

//BlogWithBLOBs.java的程式碼
package com.online.domain;
public class BlogWithBLOBs extends Blog {
    private String content;
    private String htmlcontent;
    //省略get和set方法
}

在mapper.xml中可以看出ResultMapWithBLOBs繼承於BaseResultMap:

<mapper namespace="com.online.dao.BlogMapper" >
  <resultMap id="BaseResultMap" type="com.online.domain.Blog" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="summary" property="summary" jdbcType="VARCHAR" />
  </resultMap>
  <resultMap id="ResultMapWithBLOBs" type="com.online.domain.BlogWithBLOBs" extends="BaseResultMap" >
    <result column="content" property="content" jdbcType="LONGVARCHAR" />
    <result column="htmlContent" property="htmlcontent" jdbcType="LONGVARCHAR" />
  </resultMap>

當然也可以去除BlogWithBLOBs.java類,解決方法是在generatorConfig.xml中對text等型別的欄位進行型別轉換,然後刪除之前生成的檔案,重新逆向生成,BlogWithBLOBs類就消失了:

<!-- 指定資料庫表     資料庫表名:tableName   對應的實體類名:domainObjectName -->
<table tableName="blog" domainObjectName="Blog">
   <columnOverride column="content" javaType="java.lang.String" jdbcType="TEXT" />
   <columnOverride column="htmlContent" javaType="java.lang.String" jdbcType="TEXT" />
</table>

三、逆向工程生成檔案的使用

public class GeneratorTest {
    public SqlSessionFactory getSqlSessionFactory() throws Exception {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

    //根據id查詢,查詢id為1的資料
    @Test
    public void testMBG01() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            Blog blog = mapper.selectByPrimaryKey(1);
            System.out.println(blog.getTitle());
        } finally {
            session.close();
        }
    }

    //沒有條件的情況,查詢全部資訊
    @Test
    public void testMBG02() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);
            List<Blog> emps = mapper.selectByExample(null);
            for (Blog blog : emps) {
                System.out.println(blog.getTitle());
            }
        } finally {
            session.close();
        }
    }

    //按照條件查詢
    @Test
    public void testMBG03() throws Exception {
        SqlSessionFactory ssf = getSqlSessionFactory();
        SqlSession session = ssf.openSession();
        try {
            BlogMapper mapper = session.getMapper(BlogMapper.class);

            //查詢欄位Summary包含愛好關鍵字的Blog物件
            BlogExample example = new BlogExample();

            BlogExample.Criteria criteria = example.createCriteria();
            criteria.andSummaryLike("%愛好%");

            List<Blog> emps = mapper.selectByExample(example);
            for (Blog blog : emps) {
                System.out.println(blog.getSummary());
            }
        } finally {
            session.close();
        }
    }
}

四、方法的介面解析(此部分來源網路)

1、mapper介面中的函式及方法

方法 功能說明
int countByExample(UserExample example) thorws SQLException 按條件計數
int deleteByPrimaryKey(Integer id) thorws SQLException 按主鍵刪除
int deleteByExample(UserExample example) thorws SQLException 按條件查詢
String/Integer insert(User record) thorws SQLException 插入資料(返回值為插入成功的個數)
User selectByPrimaryKey(Integer id) thorws SQLException 按主鍵查詢
ListselectByExample(UserExample example) thorws SQLException 按條件查詢
ListselectByExampleWithBLOGs(UserExample example) thorws SQLException 按條件查詢(包括BLOB欄位)。只有當資料表中的欄位型別有為二進位制的才會產生。
int updateByPrimaryKey(User record) thorws SQLException 按主鍵更新
int updateByPrimaryKeySelective(User record) thorws SQLException 按主鍵更新值不為null的欄位
int updateByExample(User record, UserExample example) thorws SQLException 按條件更新
int updateByExampleSelective(User record, UserExample example) thorws SQLException 按條件更新值不為null的欄位

2、example例項解析
mybatis的逆向工程中會生成例項及例項對應的example,example用於新增條件,相當where後面的部分 。
xxxExample example = new xxxExample();
Criteria criteria = new Example().createCriteria();

方法 說明
example.setOrderByClause(“欄位名 ASC”) 添加升序排列條件,DESC為降序
example.setDistinct(false) 去除重複,boolean型,true為選擇不重複的記錄。
criteria.andXxxIsNull 新增欄位xxx為null的條件
criteria.andXxxIsNotNull 新增欄位xxx不為null的條件
criteria.andXxxEqualTo(value) 新增xxx欄位等於value條件
criteria.andXxxNotEqualTo(value) 新增xxx欄位不等於value條件
criteria.andXxxGreaterThan(value) 新增xxx欄位大於value條件
criteria.andXxxGreaterThanOrEqualTo(value) 新增xxx欄位大於等於value條件
criteria.andXxxLessThan(value) 新增xxx欄位小於value條件
criteria.andXxxLessThanOrEqualTo(value) 新增xxx欄位小於等於value條件
criteria.andXxxIn(List<?>) 新增xxx欄位值在List<?>條件
criteria.andXxxNotIn(List<?>) 新增xxx欄位值不在List<?>條件
criteria.andXxxLike(“%”+value+”%”) 新增xxx欄位值為value的模糊查詢條件
criteria.andXxxNotLike(“%”+value+”%”) 新增xxx欄位值不為value的模糊查詢條件
criteria.andXxxBetween(value1,value2) 新增xxx欄位值在value1和value2之間條件
criteria.andXxxNotBetween(value1,value2) 新增xxx欄位值不在value1和value2之間條件

三、應用舉例
1.查詢
① selectByPrimaryKey()

User user = XxxMapper.selectByPrimaryKey(100); //相當於select* from user where id = 100 

② selectByExample() 和selectByExampleWithBLOGs()

UserExample example = newUserExample(); 
Criteriacriteria = example.createCriteria(); 
criteria.andUsernameEqualTo("wyw"); 
criteria.andUsernameIsNull(); 
example.setOrderByClause("username asc,email desc"); 
List<?>list = XxxMapper.selectByExample(example); 
//相當於:select * from user where username = 'wyw' and username is null order by username asc,email desc 

注:在逆向工程生成的檔案XxxExample.Java中包含一個static的內部類Criteria,Criteria中的方法是定義SQL 語句where後的查詢條件。

2.插入資料
①insert()

User user = new User(); 
user.setId("dsfgsdfgdsfgds"); 
user.setUsername("admin"); 
user.setPassword("admin") 
user.setEmail("[email protected]"); 
XxxMapper.insert(user); 
//相當於:insert intouser(ID,username,password,email) values ('dsfgsdfgdsfgds','admin','admin','[email protected]'); 

3.更新資料
①updateByPrimaryKey()

User user =new User(); 
user.setId("dsfgsdfgdsfgds"); 
user.setUsername("wyw"); 
user.setPassword("wyw"); 
user.setEmail("[email protected]"); 
XxxMapper.updateByPrimaryKey(user); 
//相當於:update user set username='wyw', password='wyw', email='[email protected]'where id='dsfgsdfgdsfgds' 

②updateByPrimaryKeySelective()

User user = new User(); 
user.setId("dsfgsdfgdsfgds"); 
user.setPassword("wyw"); 
XxxMapper.updateByPrimaryKey(user); 
//相當於:update user set password='wyw' where id='dsfgsdfgdsfgds' 

③ updateByExample() 和updateByExampleSelective()

UserExample example = new UserExample(); 
Criteria criteria = example.createCriteria(); 
criteria.andUsernameEqualTo("admin"); 
User user = new User(); 
user.setPassword("wyw"); 
XxxMapper.updateByPrimaryKeySelective(user,example); 
//相當於:update user set password='wyw' where username='admin' 
updateByExample()更新所有的欄位,包括欄位為null的也更新,建議使用 updateByExampleSelective()更新想更新的欄位 

4.刪除資料
①deleteByPrimaryKey()

XxxMapper.deleteByPrimaryKey(1);  //相當於:deletefrom user where id=1 

②deleteByExample()

UserExample example = new UserExample(); 
Criteria criteria = example.createCriteria(); 
criteria.andUsernameEqualTo("admin"); 
XxxMapper.deleteByExample(example); 
//相當於:delete from user where username='admin' 

數量
①countByExample()

UserExample example = new UserExample(); 
Criteria criteria = example.createCriteria(); 
criteria.andUsernameEqualTo("wyw"); 
int count = XxxMapper.countByExample(example); 
//相當於:select count(*) from user where username='wyw'