10、ssm中通用mapper的使用及通用mapper中的常用方法

一、ssm中通用mapper的配置使用

1、pom.xml中 添加依赖


        
            tk.mybatis
            mapper
            3.1.2
        

2、Spring-mybatis.xml中的配置
注:spring-mybatis整合一起,不再需要mybatis-config.xml文件

   
            
             
                
                    
                    
                        
                            IDENTITY=MYSQL
                            seqFormat={0}.nextval
                            
                            mappers=tk.mybatis.mapper.common.Mapper
                        
                    
                
            
        
    

3、在dao包中写dao接口继承Mapper接口,注意一定要写泛型
这样就继承了Mapper中的增删改查的基本方法,不用再写mapper映射文件。

  public interface CommentMapper extends Mapper {
    }   

二、通用mapper介绍

1、通用mapper介绍

通用Mapper都可以极大的方便开发人员。可以随意的按照自己的需要选择通用方法,还可以很方便的开发自己的通用方法。
极其方便的使用MyBatis单表的增删改查。支持单表操作,
**不支持通用的多表联合查询。**

特别强调 @Transient

如果你的实体类中包含了不是数据库表中的字段,你需要给这个字段加上@Transient注解,
这样通用Mapper在处理单表操作时就不会将标注的属性当成表字段处理!

2、使用方式
继承通用的Mapper,必须指定泛型

public interface UserMapper extends Mapper{
   //其他代码
}

三、通用mapper常用方法

mapper继承了baseMapper、ExampleMapper、RowBoundsMapper**
其中baseMapper中的主要方法如下

1、基础接口select

List select(T record)
根据T对象中的属性名称查询,类似于select * from table where t.name=#{name} and t.password = #{password}
T selectOne(T record)
根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
T selectByPrimaryKey(Object key)
根据主键查询
说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
int selectCount(T record);
说明:根据实体中的属性查询总数,查询条件使用等号

2、基础接口insert

int insert(T record);
说明:保存一个实体,null的属性也会保存,不会使用数据库默认值
方法:int insertSelective(T record);
说明:保存一个实体,null的属性不会保存,会使用数据库默认值

insert 和insertSelective的区别
01、insert插入数据时,会把所有属性都插入一遍,不管是否为空,不会使用数据库默认值

假如:User类有三个属性,id,name,password     id是自增的
例:User user=new User();
user.setName("姚明");
userMapper.insert(userService);

运行的时候,显示的sql语句如下:(主键是自动添加,默认为null)
INSERT INTO User (id,name,password) VALUES ( ?,?,? )
Parameters: null, 姚明(String), null    

02、insertSelective插入数据时,只插入不为空的数据,会使用数据库默认值

假如:User类有三个属性,id,name,password     id是自增的
例:User user=new User();
user.setName("姚明");
userMapper.insert(userService);

运行的时候,显示的sql语句如下:
INSERT INTO User (name) VALUES ( ?) 
Parameters: 姚明(String) 

3、基础接口Update
二者的区别类似于insert和insertSelsctive

方法:int updateByPrimaryKey(T record);
说明:根据主键更新实体全部字段,null值会被更新
方法:int updateByPrimaryKeySelective(T record);
说明:根据主键更新属性不为null的值

4、基础接口delete

方法:int delete(T record);
说明:根据实体属性作为条件进行删除,查询条件使用等号
方法:int deleteByPrimaryKey(Object key);
说明:根据主键字段进行删除,方法参数必须包含完整的主键属性

参考
https://blog.csdn.net/wtopps/article/details/70232866
https://blog.csdn.net/miss_yinghao/article/details/78560437

你可能感兴趣的:(ssm框架)