11通用mapper

 

目前通用mapper只支持对单表的操作,对单表的增删改查,无需在mapper.xml写对应的sql语句,只需要我们调用相应的接口,对于快速开发极为方便。

1.首先在maven项目,在pom.xml中引入mapper的依赖

  1.  

    <dependency>
    
    <groupId>tk.mybatis</groupId>
    
    <artifactId>mapper</artifactId>
    
    <version>3.3.8</version>
    
    </dependency>

     


2.Spring配置文件中加入扫描路径

  1.  

    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
    
    <property name="basePackage" value="com.xinnet.**.mapper" />
    
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    
    </bean>

     

 

3.实体类设置主键

 
  1.  

@Table(name = "op_virtual_ip")

public class VirtualIpBean {

  //主键

    @Id

    Long id;

@Column

String data;

}


 

4.业务mapper接口继承通用mapper,并只定实体泛型

 
  1.  

    import tk.mybatis.mapper.common.Mapper;
    
    public interface IVirtualIPMapper extends Mapper<VirtualIpBean> {
    
    
    }

     

5.业务mapper接口的实际使用

 
  1.  

    import java.util.Date;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.stereotype.Service;
    
    import tk.mybatis.mapper.entity.Example;
    
    
    @Service
    
    public class VirtualIpService {
    
      @Autowired
    
      IVirtualIPMapper vipMapper;
    
      public void test(){
    
        VirtualIpBean vipBean = new VirtualIpBean();
    
        vipBean.setBeginTime(new Date());
    
        //(1)mapper基础接口
    
        //select接口
    
    List<VirtualIpBean> vipList = vipMapper.select(vipBean);//根据实体中的属性值进行查询,查询条件使用等号
    
        VirtualIpBean vip = vipMapper.selectOne(vipBean);//根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
    
        List<VirtualIpBean> vipList2 = vipMapper.selectAll();//查询全部结果,select(null)方法能达到同样的效果
    
        VirtualIpBean vip2 = vipMapper.selectByPrimaryKey(1);//根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
    
        int count = vipMapper.selectCount(vipBean);//根据实体中的属性查询总数,查询条件使用等号
    
        //insert接口
    
        int a = vipMapper.insert(vipBean);//保存一个实体,null的属性也会保存,不会使用数据库默认值
    
        int a1 = vipMapper.insertSelective(vipBean);//保存实体,null的属性不会保存,会使用数据库默认值
    
        //update接口
    
        int b = vipMapper.updateByPrimaryKeySelective(vipBean);//根据主键更新属性不为null的值
    
        int c = vipMapper.updateByPrimaryKey(vipBean);//根据主键更新实体全部字段,null值会被更新
    
        //delete接口
    
        int d = vipMapper.delete(vipBean);//根据实体属性作为条件进行删除,查询条件使用等号
    
        int e = vipMapper.deleteByPrimaryKey(1);//根据主键字段进行删除,方法参数必须包含完整的主键属性
    
        //(2)Example方法
    
        Example example = new Example(VirtualIpBean.class);
    
        example.createCriteria().andEqualTo("id", 1);
    
        example.createCriteria().andLike("val", "1");
    
        //自定义查询
    
        List<VirtualIpBean> vipList3 = vipMapper.selectByExample(example);
    
      }
    
    }

    11通用mapper

11通用mapper