栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis

一、mybatis的使用
  1. 使用mybatis需要添加mybatis的依赖,同时由于mybatis在是对jdbc的封装,也需要引入对应数据库的jdbc依赖
  2. 配置mybatis,在resources目录下创建一个mybatis-config.xml文件,然后输入以下类容(可以在官网上找到配置类容链接)



  
  
    
  	  
      
      
      
      	
        
        
        
       	
        
        
      
    
  
  
  
    
  

  1. 创建SqlSession,mybatis对于数据库的操作需要依赖于SqlSession对象。
		SqlSession session = null;
        try {
        	
            Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
            
            session = factory.openSession();
            Connection connection = session.getConnection();
            System.out.println(connection);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(session != null)
                session.close();
        }
二、执行crud

mybatis是对JDBC的封装,在JDBC中SQL语句与代码混在一起,mybatis实现了业务逻辑代码与SQL语句的解耦。所有的SQL语句都写在xml文件中,session对象负责执行这些SQL语句并且进行封装。在resources目录下新建mappers文件夹,在里面新建xml文件用来保存SQL语句。可以从官网上粘贴对应的dtd,所有的SQL语句都书写在mapper标签内,其中namespace指定当前xml文件的命名空间,需要注意的是这些语句是根据namespace和namespace里面语句的id来区分的。

  1. 查询


	
	
        select * from t_goods
    

执行查询语句

@Test
public void testReturnMap(){
	SqlSession session = null;
	try {
		
		session = MyBatisUtil.openSession();
		
		List goods = session.selectList("goods.returnMap");
		for(Map map : goods)
			System.out.println(map);
	}catch (Exception e){
		e.printStackTrace();
	}finally {
		if(session != null)
		session.close();
	}
}

对于查询语句的返回结果,mybatis可以直接将结果包装成的实体对象,这个实体对象中不应该包含自定义的对象。查询语句可能输入参数,可以只传入一个参数,也可以使用Map对象
实体类:

package com.zyf.mybatis.Entity;

import java.io.Serializable;

public class Goods  implements Serializable {
    private Integer goodsId;
    private String title;
    private String subTitle;
    private Float originalCost;
    private Float currentPrice;
    private Float discount;
    private Integer isFreeDelivery;
    private Integer categoryID;

    public Goods() {
    }

    public Goods(String title, String subTitle, Float originalCost, Float currentPrice, Float discount, Integer isFreeDelivery, Integer categoryID) {
        this.title = title;
        this.subTitle = subTitle;
        this.originalCost = originalCost;
        this.currentPrice = currentPrice;
        this.discount = discount;
        this.isFreeDelivery = isFreeDelivery;
        this.categoryID = categoryID;
    }

    public Integer getGoodsId() {
        return goodsId;
    }

    public String getTitle() {
        return title;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public Float getOriginalCost() {
        return originalCost;
    }

    public Float getCurrentPrice() {
        return currentPrice;
    }

    public Float getDiscount() {
        return discount;
    }

    public Integer getIsFreeDelivery() {
        return isFreeDelivery;
    }

    public Integer getCategoryID() {
        return categoryID;
    }

    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public void setOriginalCost(Float originalCost) {
        this.originalCost = originalCost;
    }

    public void setCurrentPrice(Float currentPrice) {
        this.currentPrice = currentPrice;
    }

    public void setDiscount(Float discount) {
        this.discount = discount;
    }

    public void setIsFreeDelivery(Integer isFreeDelivery) {
        this.isFreeDelivery = isFreeDelivery;
    }

    public void setCategoryID(Integer categoryID) {
        this.categoryID = categoryID;
    }

    @Override
    public String toString() {
        return this.getGoodsId()+"-"+this.getTitle()+"-"+this.getSubTitle()+"-"+this.getOriginalCost()+
                "-"+this.getCurrentPrice()+"-"+this.getDiscount()+"-"+this.getIsFreeDelivery()+"-"+
                this.getCategoryID();
    }
}

查询语句:



	select * from t_goods where current_price between #{min} and #{max}

执行查询语句:

@Test
public void testSelectById(){
	SqlSession session = null;
	try {
		session = MyBatisUtil.openSession();
		Goods goods = session.selectOne("goods.selectById", 5739);
		System.out.println(goods);
	}catch (Exception e){
		e.printStackTrace();
	}finally {
		if(session != null)
		session.close();
	}
}
@Test
public void testSelectByPrice(){
	SqlSession session = null;
	try {
		session = MyBatisUtil.openSession();
		Map map = new HashMap();
		map.put("min" , 500);
		map.put("max", 1000);
		List goods = session.selectList("goods.selectByPrice", map);
		System.out.println(goods);
	}catch (Exception e){
		e.printStackTrace();
	}finally {
		if(session != null)
			session.close();
	}
}

对于简单的对象(属性中不包含自定义对象),mybatis可以进行自定义的封装,对于复杂的对象,需要通过resultMap来指定表的列和对象的映射规则。
实体对象:

package com.zyf.mybatis.dto;
import com.zyf.mybatis.Entity.Goods;
public class GoodsDTO {
    private Goods goods;
    private String categoryName;
    public Goods getGoods() {
        return goods;
    }
    public void setGoods(Goods goods) {
        this.goods = goods;
    }
    public String getCategoryName() {
        return categoryName;
    }
    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }
    @Override
    public String toString() {
        return "GoodsDTO{" +
                "goods=" + goods +
                ", categoryName='" + categoryName + ''' +
                '}';
    }
}

xml文件:



	
	
	
	
	
	
	
	
	


        select * from t_goods_detail where goods_id = #{value}
    
    
    
        
        
        
        
    
    
        select * from t_goods limit 1,10
    
三、动态SQL

mybatis支持使用,,等标签动态生成SQL语句

    
        select * from t_goods where goods_id = #{value}
    
  1. 不放入缓冲区
    对于查询结果为集合的语句,这个集合被设为一个对象存放在缓冲区中,只有在查询结果与这个集合中的所有内容都相同时才会去缓冲区中取这个集合,命中率较低,因此可以设置某条查询语句的查询结果不放入缓冲区中,使用useCache=“false”,这个貌似不对一个session起作用。