之前用Mybatis框架反向的實體,還有實體里面的Example,之前只是知道Example里面放的是條件查詢的方法,可以一直不知道怎么用,到今天才開始知道怎么簡單的用。
在我們前台查詢的時候會有許多的條件傳過來:先看個例子:
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的方法,里面
andUsernameEqualToandPasswordEqualTo
都是在生成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.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();
}
}
javaBeans類的成員變量一般稱為屬性(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">
map類型
傳入map類型,直接通過#{keyname}就可以引用到鍵對應的值。使用@param注釋的多個參數值也會組裝成一個map數據結構,和直接傳遞map進來沒有區別。
mapper接口:
int updateByExample(@Param("user") User user, @Param("example") UserExample example);
sql映射:
<update id="updateByExample" parameterType="map" >
update tb_user set id = #{user.id,jdbcType=INTEGER}, ...
<if test="_parameter != null" >
<include refid="Update_By_Example_Where_Clause" />
</if>
注意這里測試傳遞進來的map是否為空,仍然使用_parameter
再來看看我的項目中的,我寫的是項目的接口開發,前端要穿寫條件進來查詢,前端的傳參格式:
{
"currPage": 0,
"startRow": 0,
"pageSize": 20,
"map":{
"andStealtollTypeEqualTo":1
}
}
注意map里面的傳的參數格式:全部是example里面的參數格式,如果還要傳入什么參數直接在里面加(相當於前端傳過來的條件),這些條件全部放進map里面。
HisVehReviewHandleExample example = new HisVehReviewHandleExample();
example.setPage(page);//將前面傳過來的page數據放進example中
popQeuryExample(example.getPage().getMap(), example.createCriteria());
vehReviewService.queryPage(example);
Map<String, Object> map = new HashMap<String, Object>();
map.put("page", page);
//map.put("typeCount", value);
result.setData(map);
writeJson(response, JSON.toJSON(result));
service層:
public Page<HisVehReviewHandle> queryPage(HisVehReviewHandleExample example) {
Page<HisVehReviewHandle> page = example.getPage();
List<HisVehReviewHandle> list = HisVehReviewHandleMapper.selectByExample(example);
System.out.println("查詢list成功"+list.get(0).getStealtollType()+" "+list.get(0).getStealtollTypeName());
int count = HisVehReviewHandleMapper.countByExample(example);
page.setRows(list);
page.setTotalCount(count);
return page;
}
sql語句查詢exaple的:
<select id="selectByExample" parameterType="com.vrview.ssm.model.example.HisVehReviewHandleExample" resultMap="BaseResultMap">
<!--
WARNING -
This element is automatically generated by MyBatis Generator, do not modify.
This element was generated on Wed Jan 17 10:03:58 CST 2018.
-->
<include refid="OracleDialectPrefix" />
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from HIS_VEH_REVIEW_HANDLE
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
<include refid="OracleDialectSuffix" />
</select>
sql語句,用來查詢數量的:
<select id="countByExample" parameterType="com.vrview.ssm.model.example.HisVehReviewHandleExample" resultType="java.lang.Integer">
select count(*) from HIS_VEH_REVIEW_HANDLE
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
關於參數_paramerter:參考:http://blog.csdn.net/u014476019/article/details/45878771
這部分就是對criteria里面的參數進行判斷,進而根據條件查詢。
<sql id="Example_Where_Clause"><where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<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 close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
