传入参数id, 查询记录
<!--传入Int型, 用对象接收-->
<select id="selectById" parameterType="Integer" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods where goods_id=#{value}
</select>
parameterType: 传入的类型
resultType: 返回的类型
#{} : 传值
SqlSession session=null;
try{
session=MyBatisUtils.openSession();
Goods goods=session.selectOne("goods.selectById",1602);
}catch(Exception e){
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
利用map传入多个值进行查询.
<!--传入map, 用对象接收-->
<select id="selectByPriceRange" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
select * from t_goods
where
current_price between #{min} and #{max}
order by current_price
limit 0,#{limt}
</select>
parameterType: java.util.Map
SqlSession session=null;
try{
session=MyBatisUtils.openSession();
Map.param=new HashMap();
param.put("min",100);
param.put("max",500);
param.put("limt",10);
List<Goods> goods=session.selectList("selectByPriceRange",param);
}catch(Exception e){
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
查询数据, 不用对象接收, 用Map来接收
<!--
利用LinkedHashMap保存多表关联结果
MyBatis会将每一条记录包装为LinkedHashMap对象
key是字段名, value是字段对应的值, 字段类型根据表结构进行自动判断
优点: 易于扩展, 易于使用
缺点: 太过灵活, 无法进行编译时检查
-->
<select id="selectGoodsMap" resultType="java.util.Map">
select g.*,c.category_name from t_goods g, t_category c
where g.category_id=c.category_id
</select>
SqlSession session=null;
try{
session=MyBatisUtils.openSession();
List<Map> list= session.selectList("goods.selectGoodsMap");
for(Map map:list){
System.out.println(map);
}
}catch(Exception e){
throw e;
}finally{
MyBatisUtils.closeSession(session);
}
复合查询, 用对象接收
public class GoodsDTO{
private Goods goods=new Goods();
private String categoryName;
private String test;
... 省略setter和getter
}
<resultMap id="rmGoods" type="com.imooc.mybatis.dto.GoodsDTO">
<id property="goods.goodsId" column="goods_id"></id>
<result property="goods.title" column="title"></result>
<result property="goods.originalCost" column="original_cost"></result>
<result property="goods.currentPrice" column="current_price"></result>
<result property="goods.discount" column="discount"></result>
<result property="goods.isFreeDelivery" column="is_free_delivery"></result>
<result property="goods.categoryId" column="category_id"></result>
<result property="categoryName" column="categoryName"></result>
<result property="test" column="test"></result>
</resultMap>
<select id="selectGoodsDTO" resultMap="rmGoods">
select g.* , c.category_name , '1' as test from t_goods g , t_category c
where g.category_id = c.category_id
</select>
session=MyBatisUtils.openSession();
List<GoodsDTO> list=session.selectList("goods.selectGoodsDTO");
for(GoodsDTO g : list){
System.out.println(g.getGoods().getTitle());
}
配置中的特殊符号
符号 | 转义 |
---|---|
& | & |
< | < |
> | > |
" | " |
’ | ' |