一、什么是example類
mybatis-generator會為每個字段產生如上的Criterion,如果表的字段比較多,產生的Example類會十分龐大。理論上通過example類可以構造你想到的任何篩選條件。在mybatis-generator中加以配置,配置數據表的生成操作就可以自動生成example了。具體配置可以參考MBG有關配置。
下面是mybatis自動生成example的使用。
二、了解example成員變量
//升序還是降序
//參數格式:字段+空格+asc(desc)
protected String orderByClause;
//去除重復
//true是選擇不重復記錄
protected boolean distinct;
//自定義查詢條件
//Criteria的集合,集合中對象是由or連接
protected List<Criteria> oredCriteria;
//內部類Criteria包含一個Cretiron的集合,
//每一個Criteria對象內包含的Cretiron之間
//是由AND連接的
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
//是mybatis中逆向工程中的代碼模型
protected abstract static class GeneratedCriteria
{…..}
//是最基本,最底層的Where條件,用於字段級的篩選
public static class Criterion {……}
三、example使用前的准備
比如我的example是根據user表生成的,UserMapper屬於dao層,UserMapper.xml是對應的映射文件
UserMapper接口:
long countByExample(CompetingStoreExample example);
List<CompetingStore> selectByExample(CompetingStoreExample example);
在我們的測試類里:
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
四、查詢用戶數量
long count = UserMapper.countByExample(example);
類似於:select count(*) from user
五、where條件查詢或多條件查詢
example.setOrderByClause("age asc");//升序
example.setDistinct(false);//不去重
if(!StringUtils.isNotBlank(user.getName())){
Criteria.andNameEqualTo(user.getName());
}
if(!StringUtils.isNotBlank(user.getSex())){
Criteria.andSexEqualTo(user.getSex());
}
List<User> userList=userMapper.selectByExample(example);
類似於:select * from user where name={#user.name} and sex={#user.sex} order by age asc;
UserExample.Criteria criteria1 = example.createCriteria();
UserExample.Criteria criteria2 = example.createCriteria();
if(!StringUtils.isNotBlank(user.getName())){
Criteria1.andNameEqualTo(user.getName());
}
if(!StringUtils.isNotBlank(user.getSex())){
Criteria2.andSexEqualTo(user.getSex());
}
Example.or(criteria2);
List<User> userList=userMapper.selectByExample(example);
類似於:select * from user where name={#user.name} or sex={#user.sex} ;
六、模糊查詢
if(!StringUtils.isNotBlank(user.getName())){
criteria.andNameLIke(‘%’+name+’%’);
}
List<User> userList=userMapper.selectByExample(example);
類似於:select * from user where name like %{#user.name}%
七、分頁查詢
int start = (currentPage - 1) * rows;
//分頁查詢中的一頁數量
example.setPageSize(rows);
//開始查詢的位置
example.setStartRow(start);
List<User> userList=userMapper.selectByExample(example);
類似於:select * from user limit start to rows
在使用常規的mybatis時,我們經常碰到的問題就是條件式查詢。在一個查詢界面,查詢條件較多,並且運算符並不總是=時,在后台就需要拼裝sql語句。這種處理方式肯定不是使用mybatis的初衷,對於使用了hibernate的我來說,如果mybatis也有一套criteria查詢就好了。在具體實現中,我們只需要按照hibernate的處理方式定義好相應的criteria,最后傳遞給mybatis,其自身處理相應的條件和參數信息,最終返回相應的數據即可.
在我們前台查詢的時候會有許多的條件傳過來:先看個例子:
public List<Contact> searchByExample(Contact contact) {
System.out.println("searchByExampleContact");
ContactExample example = new ContactExample();
ContactExample.Criteria cri = example.createCriteria();
// //////////////////////////////////////////////////////////
if (this.objectAttrNullCheck(contact, "username"))
cri.andUsernameEqualTo(contact.getUsername());
if (this.objectAttrNullCheck(contact, "password"))
cri.andPasswordEqualTo(contact.getPassword());
ContactMapper vcontactMapper = sqlSession
.getMapper(ContactMapper.class);
List<Contact> returnList = vcontactMapper.selectByExample(example);
return returnList;
}
這是簡單的用戶登錄的后台代碼,example中有一個Criterria的方法,里面
andUsernameEqualTo
andPasswordEqualTo
都是在生成example的時候生成的。這兩個方法是判斷單值的。
簡單介紹下,都是百度的:
Criteria
Criteria包含一個Cretiron的集合,每一個Criteria對象內包含的Cretiron之間是由AND連接的,是邏輯與的關系。
oredCriteria
Example內有一個成員叫oredCriteria,是Criteria的集合,就想其名字所預示的一樣,這個集合中的Criteria是由OR連接的,是邏輯或關系。oredCriteria就是ORed Criteria。
其他
Example類的distinct字段用於指定DISTINCT查詢。
orderByClause字段用於指定ORDER BY條件,這個條件沒有構造方法,直接通過傳遞字符串值指定。
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
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.apache.log4j.pattern.ClassNamePatternConverter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.ssm.mapper.ItemsMapper;
import cn.itcast.ssm.po.ItemsExample;
public class Student {
public static void main(String[] args) throws IOException {
/*方式一 */
ItemsExample itemsExample1 = new ItemsExample();
itemsExample1.or().andIdEqualTo(5).andNameIsNotNull();
itemsExample1.or().andPicEqualTo("xxx").andPicIsNull();
List<Integer> fieldValues = new ArrayList<Integer>();
fieldValues.add(8);
fieldValues.add(11);
fieldValues.add(14);
fieldValues.add(22);
itemsExample1.or().andIdIn(fieldValues);
itemsExample1.or().andIdBetween(5, 9);
/* 方式二 criteria1與criteria2是or的關系 */
ItemsExample itemsExample2 = new ItemsExample();
ItemsExample.Criteria criteria1 = itemsExample2.createCriteria();
criteria1.andIdIsNull();
criteria1.andPriceEqualTo((float) 3);
ItemsExample.Criteria criteria2 = itemsExample2.createCriteria();
criteria2.andNameIsNull();
criteria2.andIdGreaterThanOrEqualTo(5);
itemsExample2.or(criteria2);
//方式一和方式二是等價的
// spring獲取mapper代理對象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
ItemsMapper itemsMapper = (ItemsMapper) applicationContext.getBean("itemsMapper");
itemsMapper.countByExample(itemsExample2);
// 獲取SqlSessionFactory
String resource = "SqlMapConfig.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
// 獲取SqlSession
SqlSession sqlSession = sqlMapper.openSession();
}
}
avaBeans類的成員變量一般稱為屬性(property)。對每個屬性訪問權限一般定義為private或protected,而不是定義為public的。注意:屬性名必須以小寫字母開頭。
對每個屬性,一般定義兩個public方法,它們分別稱為訪問方法(getter)和修改方法(setter),允許容器訪問和修改bean的屬性。
public String getColor();
public void setColor(String);
一個例外是當屬性是boolean類型時,訪問器方法應該定義為isXxx()形式。
對象類型
雖然可以明確的引用對象的屬性名了,但如果要在if元素中測試傳入的user參數,仍然要使用_parameter來引用傳遞進來的實際參數,因為傳遞進來的User對象的名字是不可考的。如果測試對象的屬性,則直接引用屬性名字就可以了。
測試user對象和傳入對象屬性
<if test="_parameter != null">
<if test="name != null">
example如何使用?
簡單查詢
這個例子展示了如何用生成后的Example類去生成一個簡單的where子句:
TestTableExample example = new TestTableExample();
example.createCriteria().andField1EqualTo(5);
作為另一種選擇, 下面的方式也是可以的:
TestTableExample example = new TestTableExample();
example.or().andField1EqualTo(5);
在上面的例子中, 動態生成的where子句是:
where field1 = 5
下面的例子展示了如何用生成后的Example類去生成一個復雜的where子句 (用到了 JSE 5.0 的泛型):
TestTableExample example = new TestTableExample();
example.or()
.andField1EqualTo(5)
.andField2IsNull();
example.or()
.andField3NotEqualTo(9)
.andField4IsNotNull();
List field5Values = new ArrayList();
field5Values.add(8);
field5Values.add(11);
field5Values.add(14);
field5Values.add(22);
example.or()
.andField5In(field5Values);
example.or()
.andField6Between(3, 7);
在上面的例子中, 動態生成的where子句是:
where (field1 = 5 and field2 is null)
or (field3 <> 9 and field4 is not null)
or (field5 in (8, 11, 14, 22))
or (field6 between 3 and 7)
將會返回滿足這些條件的記錄結果.
去重復查詢
您可以在所有的Example類中調用 setDistinct(true) 方法進行強制去重復查詢.
Criteria類
Criteria 內部類的每個屬性都包含 andXXX 方法,以及如下的標准的SQL查詢方法:
IS NULL - 指相關的列必須為NULL
IS NOT NULL - 指相關的列必須不為NULL
= (equal) - 指相關的列必須等於方法參數中的值
<> (not equal) - 指相關的列必須不等於方法參數中的值
(greater than) - 指相關的列必須大於方法參數中的值
= (greater than or equal) - 指相關的列必須大於等於方法參數中的值
< (less than) - 指相關的列必須小於於方法參數中的值
<= (less than or equal) - 指相關的列必須小於等於方法參數中的值
LIKE - 指相關的列必須 “like” 方法參數中的值. 這個方法不用必須加入 ‘%’, 您必須設置方法參數中的值.
NOT LIKE - 指相關的列必須 “not like” 方法參數中的值. 這個方法不用必須加入 ‘%’, 您必須設置方法參數中的值.
BETWEEN - 指相關的列必須在 “between” 方法參數中的兩個值之間.
NOT BETWEEN - 指相關的列必須不在 “not between” 方法參數中的兩個值之間.
IN - 指相關的列必須在傳入的方法參數的list中.
NOT IN - 指相關的列必須不在傳入的方法參數的list中.
如何生成Example類?
mybatis的的配置文件可以使用mybatis-generator工具生成,它就可以幫我們生成example類。
————————————————
版權聲明:本文為CSDN博主「糯米小粥」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u014756578/article/details/86490052