Mybatis中的通用mapper的使用

Mybatis中的通用mapper的使用
1、在maven中添加依赖
<dependency>
    <groupId>com.github.abel533</groupId>
    <artifactId>mapper</artifactId>
    <version>2.3.4</version>
</dependency>
2、集成通用mapper
对com.github.abel533.mapper.Mapper的集成,实际上是配置MapperHelper。一共有三种方式:针对Java编码、和Spring集成和使用拦截器配置。
(1)Java编码
对于单独使用Mybatis,首先通过如下方式创建sqlSessionFactory:
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
之后直接使用JAVA编码,可以在初始化sqlSessionFactory的地方按照下面的方式操作:
//从上面的sqlSessionFactory取出一个session
session = sqlSessionFactory.openSession();
//创建一个MapperHelper
MapperHelper mapperHelper = new MapperHelper();
// 设置UUID生成策略,配置UUID生成策略需要使用OGNL表达式
// 默认值32位长度:@java.util.UUID@randomUUID().toString().replace("-", "")
mapperHelper.setUUID("");
// 主键自增回写方法,默认值MYSQL,详细说明请看文档
mapperHelper.setIDENTITY("HSQLDB");
// 序列的获取规则,使用{num}格式化参数,默认值为{0}.nextval,
// 针对Oracle可选参数一共3个,对应0,1,2,分别为SequenceName,ColumnName, PropertyName
mapperHelper.setSeqFormat("NEXT VALUE FOR {0}");
// 设置全局的catalog,默认为空,如果设置了值,操作表时的sql会是catalog.tablename
mapperHelper.setCatalog("");
// 设置全局的schema,默认为空,如果设置了值,操作表时的sql会是schema.tablename
// 如果同时设置了catalog,优先使用catalog.tablename
mapperHelper.setSchema("");
// 主键自增回写方法执行顺序,默认AFTER,可选值为(BEFORE|AFTER)
mapperHelper.setOrder("AFTER");
// 注册通用Mapper接口
mapperHelper.registerMapper(Mapper.class);
mapperHelper.registerMapper(HsqldbMapper.class);
//配置完成后,执行下面的操作
mapperHelper.processConfiguration(session.getConfiguration());
//OK - mapperHelper的任务已经完成
上面配置参数的时候,是一个个调用set方法进行的,你还可以使用MapperHelper的MapperHelper(Properties properties)构造方法,或者调用setProperties(properties)方法,通过.properties配置文件来配置。
(2)和Spring集成
在结合Spring使用的时候,可以通过xml配置文件达到上面Java编码方式的效果。如下配置:
<bean class="com.github.abel533.mapperhelper.MapperHelper"
        depends-on="sqlSession" init-method="initMapper" scope="singleton" lazy-init="false">
    <property name="mappers">
        <array>
            <!-- 可以配置多个 -->
            <value>com.kang.mybatis.userMapper.mapper</value>
        </array>
    </property>
    <!-- 对于多数据源,这里也可以像上面这样配置多个 -->
    <property name="sqlSessions" ref="sqlSession"/>
</bean>
可以看到配置中依赖了sqlSession,所以使用这种方式,你还要在Spring的配置中保证sqlSession存在。一般情况下都会在Spring定义sqlSession。一般的定义方法如下:
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
在Spring中使用这种方式的时候,Spring启动完成的时候,所有的通用Mapper都已经处理完成了。后面就可以直接使用通用方法,不需要拦截器来执行了。
注意:目前和Spring集成的时候存在一个bug,这个bug产生的原因如下:
如果你的Mapper没有在项目启动的时候通过@Autowired注入到Service或者其他类中,那么这个Mapper是一个还没有注册到MybatisSqlSession中的Mapper,MapperHelper在启动过程中没有处理该Mapper,这就会导致dynamicSQL无法实例化一类的异常。这种情况只能使用拦截器处理。
(3)拦截器
注意这三种配置方式只需选择其一即可,无需重复配置。
基于拦截器的配置方式分为mybatis配置方式和纯spring集成方式。
首先是Mybatis配置文件方式:
在mybatis-config.xml中添加如下配置:
<plugins>
  <plugin interceptor="com.github.abel533.mapperhelper.MapperInterceptor">
    <!--================================================-->
    <!--可配置参数说明(一般无需修改)-->
    <!--================================================-->
    <!--UUID生成策略-->
    <!--配置UUID生成策略需要使用OGNL表达式-->
    <!--默认值32位长度:@java.util.UUID@randomUUID().toString().replace("-", "")-->
    <!--<property name="UUID" value="@java.util.UUID@randomUUID().toString()"/>-->
    <!--主键自增回写方法,默认值MYSQL,详细说明请看文档-->
    <property name="IDENTITY" value="HSQLDB"/>
    <!--序列的获取规则,使用{num}格式化参数,默认值为{0}.nextval,针对Oracle-->
    <!--可选参数一共3个,对应0,1,2,分别为SequenceName,ColumnName,PropertyName-->
    <property name="seqFormat" value="{0}.nextval"/>
    <!--主键自增回写方法执行顺序,默认AFTER,可选值为(BEFORE|AFTER)-->
    <!--<property name="ORDER" value="AFTER"/>-->
    <!--通用Mapper接口,多个通用接口用逗号隔开-->
    <property name="mappers" value="com.github.abel533.mapper.Mapper"/>
  </plugin>
</plugins>
然后是纯Spring配置方式:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="mapperLocations">
    <array>
      <value>classpath:mapper/*.xml</value>
      <value>classpath:com/isea533/mybatis/mapper/*.xml</value>
    </array>
  </property>
  <property name="typeAliasesPackage" value="com.isea533.mybatis.model"/>
  <property name="plugins">
    <array>
      <bean class="com.github.abel533.mapperhelper.MapperInterceptor">
        <property name="properties">
          <!-- 属性一行一个,具体属性参考mybatis-config.xml中的属性 -->
          <value>
            mappers=com.github.abel533.mapper.Mapper
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>
3、自定义接口mapper集成通用mapper
我们可以自定义mapper接口继承通用的Mapper<T>,但必须必须指定泛型<T>
例如下面的例子:
public interface UserMapper extends Mapper<User> {
}
一旦继承了Mapper<T>,继承的Mapper即UserInfoMapper就拥有了以下通用的方法:

//根据实体类不为null的字段进行查询,条件全部使用=号and条件
List<T> select(T record);


//根据实体类不为null的字段查询总数,条件全部使用=号and条件
int selectCount(T record);


//根据主键进行查询,必须保证结果唯一
//单个字段做主键时,可以直接写主键的值
//联合主键时,key可以是实体类,也可以是Map
T selectByPrimaryKey(Object key);


//插入一条数据
//支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写)
//优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长
int insert(T record);


//插入一条数据,只插入不为null的字段,不会影响有默认值的字段
//支持Oracle序列,UUID,类似Mysql的INDENTITY自动增长(自动回写)
//优先使用传入的参数值,参数值空时,才会使用序列、UUID,自动增长
int insertSelective(T record);


//根据实体类中字段不为null的条件进行删除,条件全部使用=号and条件
int delete(T key);


//通过主键进行删除,这里最多只会删除一条数据
//单个字段做主键时,可以直接写主键的值
//联合主键时,key可以是实体类,也可以是Map
int deleteByPrimaryKey(Object key);


//根据主键进行更新,这里最多只会更新一条数据
//参数为实体类
int updateByPrimaryKey(T record);


//根据主键进行更新
//只会更新不是null的数据
int updateByPrimaryKeySelective(T record);


//根据Exmaple条件查询总数
int selectCountByExample(Object example);


//根据Exmaple条件删除
int deleteByExample(Object example);


//根据Exmaple条件查询
List<T> selectByExample(Object example);


//根据Exmaple条件更新非空(null)字段
int updateByExampleSelective(@Param("record") T record, @Param("example") Object example);


//根据Exmaple条件更新全部字段
int updateByExample(@Param("record") T record, @Param("example") Object example);
但是泛型(实体类)<T>的类型必须符合如下要求:
实体类按照如下规则和数据库表进行转换,注解全部是JPA中的注解:
1)表名默认使用类名,驼峰转下划线(只对大写字母进行处理),如UserInfo默认对应的表名为user_info。
2)表名可以使用@Table(name = "tableName")进行指定,对不符合第一条默认规则的可以通过这种方式指定表名.
3)字段默认和@Column一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式.
4)可以使用@Column(name = "fieldName")指定不符合第3条规则的字段名。
5)使用@Transient注解可以忽略字段,添加该注解的字段不会作为表字段使用。
6)建议一定要配置一个@Id注解作为主键的字段,可以有多个@Id注解的字段作为联合主键。
7)默认情况下,实体类中如果不存在包含@Id注解的字段,所有的字段都会作为主键字段进行使用(这种效率极低).
8)实体类可以继承使用。
9)由于基本类型,如int作为实体类字段时会有默认值0,而且无法消除,所以实体类中建议不要使用基本类型,建议使用基本类型的包装类型如Integer,Long等类型。
除了上面提到的这些,Mapper还提供了序列(支持Oracle)、UUID(任意数据库,字段长度32)、主键自增(类似Mysql,Hsqldb)三种方式,其中序列和UUID可以配置多个,主键自增只能配置一个。
这三种方式不能同时使用,同时存在时按照 序列>UUID>主键自增的优先级进行选择.下面是具体配置方法:
1)使用序列可以添加如下的注解:
//可以用于数字类型,字符串类型(需数据库支持自动转型)的字段
@SequenceGenerator(name="Any",sequenceName="seq_userid")
@Id
private Integer id;
该字段不会回写。这种情况对应类似如下的XML:
<insert id="insertAuthor">
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (seq_userid.nextval, #{username, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
2)使用UUID时:
//可以用于任意字符串类型长度超过32位的字段
@GeneratedValue(generator = "UUID")
private String username;
该字段不会回写。这种情况对应类似如下的XML:
<insert id="insertAuthor">
  <bind name="username_bind" value='@java.util.UUID@randomUUID().toString().replace("-", "")' />
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (#{id}, #{username_bind}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
3)使用主键自增:
//不限于@Id注解的字段,但是一个实体类中只能存在一个(继承关系中也只能存在一个)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
增加这个注解后,会回写ID。
通过设置@GeneratedValue的generator参数可以支持更多的获取主键的方法,例如在Oracle中使用序列:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY,generator = "select SEQ_ID.nextval from dual")
private Integer id;
使用Oracle序列的时候,还需要配置:
<property name="ORDER" value="BEFORE"/>
因为在插入数据库前,需要先获取到序列值,否则会报错。
这种情况对于的xml类似下面这样:
<insert id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
  select SEQ_ID.nextval from dual
</selectKey>
insert into Author
  (id, username, password, email,bio, favourite_section)
values
  (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
主键自增还有一种简单的写法:
//不限于@Id注解的字段,但是一个实体类中只能存在一个(继承关系中也只能存在一个)
@GeneratedValue(generator = "JDBC")
private Integer id;
这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增字段)。 这种情况对应的xml类似下面这样:
<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
4、将通用mapper添加到Mybatis配置中
推荐使用spring集成的方式,只需要有下面的这个扫描Mapper接口的这个配置即可:如下
    <!-- 定义Mapper接口的扫描器 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.kang.mybatis.mapper"/>  
    </bean>  
如果想在Spring4中使用泛型注入,还需要包含Mapper<T>所在的包。


5、相关博客
spring集成Mybatis利用通用mapper和分页助手实现restful风格的编写


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Mybatis通用Mapper是一个基于Mybatis框架的插件,它可以帮助我们快速地进行数据库操作,避免了手写SQL的繁琐和容易出错的问题。使用Mybatis通用Mapper,我们只需要定义好实体类和Mapper接口,就可以直接调用通用的增删改查方法,非常方便。 具体使用方法如下: 1. 引入Mybatis通用Mapper的依赖包,可以通过Maven或者Gradle进行引入。 2. 定义实体类,需要注意的是实体类的属性名要和数据库表的字段名一致,或者使用@ColumnName注解进行映射。 3. 定义Mapper接口,继承通用Mapper接口,例如: public interface UserMapper extends Mapper<User> {} 4. 在Mybatis的配置文件配置通用Mapper插件,例如: <plugins> <plugin interceptor="tk.mybatis.mapper.plugin.MapperInterceptor"> <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/> </plugin> </plugins> 5. 在代码调用通用Mapper的方法,例如: @Autowired private UserMapper userMapper; public void addUser(User user) { userMapper.insert(user); } 以上就是Mybatis通用Mapper使用方法,它可以大大简化我们的开发工作,提高开发效率。 ### 回答2: Mybatis通用Mapper是一个基于Mybatis通用Mapper插件。它提供了单表的增删改查操作,同时还支持通用的批量操作和条件查询等功能。在使用Mybatis通用Mapper时,我们不需要编写繁琐的Mapper接口和对应的XML文件,只需要使用注解即可完成对数据库的操作。 首先,我们需要在pom.xml文件添加Mybatis通用Mapper的依赖: ``` <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>4.1.5</version> </dependency> ``` 接下来,我们需要在Mybatis的配置文件添加通用Mapper的配置: ``` <plugins> <plugin interceptor="tk.mybatis.mapper.common.MapperInterceptor"> <property name="mappers" value="tk.mybatis.mapper.common.BaseMapper"/> </plugin> </plugins> ``` 完成以上操作后,我们就可以在项目使用Mybatis通用Mapper了。例如,我们要对一个用户表进行操作,可以创建一个User实体类: ``` public class User { private Integer id; private String username; private String password; private String email; // 省略getter和setter方法 } ``` 然后,我们通过注解在UserMapper接口定义对用户表的操作: ``` public interface UserMapper extends Mapper<User> { } ``` 这里的MapperMybatis通用Mapper提供的一个接口,通过继承该接口,我们可以直接使用定义好的单表操作方法。 接下来,我们就可以直接在代码使用UserMapper了。例如,我们要插入一条用户记录,可以使用以下代码: ``` User user = new User(); user.setUsername("test"); user.setPassword("123456"); user.setEmail("test@example.com"); userMapper.insert(user); ``` 如果我们需要查询一条用户记录,可以使用以下代码: ``` User user = new User(); user.setId(1); User result = userMapper.selectOne(user); ``` 以上就是使用Mybatis通用Mapper的简单示例。在实际使用,我们还可以通过注解实现复杂的批量操作和条件查询等功能,具体请参考Mybatis通用Mapper的官方文档。 ### 回答3: Mybatis通用mapper是基于Mybatis的一个工具,简化了MybatisXML配置的工作量,提供了一些通用的方法,能够简化我们的增删改查操作。下面简单介绍一下Mybatis通用mapper使用方法。 一、引入依赖和配置 在pom文件引入mybatis通用mapper的依赖 ``` <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>${mybatis-mapper.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> ``` 在application.yml进行相关配置 ``` mybatis: #配置别名 type-aliases-package: com.xxxx.entity #配置xml映射文件路径 mapper-locations: classpath:mapper/*.xml mapper: #配置通用mapper的包路径 mappers: tk.mybatis.mapper.common.Mapper #配置实体类主键的生成策略 identity: mysql #配置mysql的方言,不配置通用mapper的分页插件会出错 dialect: mysql ``` 二、编写实体类和Mapper接口 在编写实体类时,需要给实体类的属性加上@TableId和@Column注解,用来指明主键和列名。例如: ``` @Data @Table(name = "user") public class User { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") private Long id; @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "age") private Integer age; @Column(name = "email") private String email; } ``` 在编写Mapper接口时,直接继承Mapper<T>接口即可,T为对应的实体类。例如: ``` @Repository public interface UserMapper extends Mapper<User> { } ``` 三、编写通用方法 Mybatis通用mapper提供了一些通用方法,例如插入数据、更新数据、删除数据和查询数据等。这些方法都可以直接调用或者根据需要进行封装。 (1)插入数据 使用通用mapper的插入方法,代码如下: ``` User user = new User(); user.setUsername("testUser"); user.setPassword("123456"); user.setAge(20); user.setEmail("testUser@xx.com"); userMapper.insert(user); ``` 使用通用mapper的批量插入方法,代码如下: ``` List<User> userList = new ArrayList<>(); User user1 = new User(); user1.setUsername("testUser1"); user1.setPassword("123456"); user1.setAge(20); user1.setEmail("testUser@xx.com"); userList.add(user1); User user2 = new User(); user2.setUsername("testUser2"); user2.setPassword("123456"); user2.setAge(21); user2.setEmail("testUser@xx.com"); userList.add(user2); userMapper.insertList(userList); ``` (2)更新数据 使用通用mapper的更新方法,代码如下: ``` User user = new User(); user.setId(1L); user.setUsername("newTestUser"); userMapper.updateByPrimaryKey(user); ``` (3)删除数据 使用通用mapper的删除方法,代码如下: ``` userMapper.deleteByPrimaryKey(1L); ``` (4)查询数据 使用通用mapper的查询方法,代码如下: ``` User user = userMapper.selectByPrimaryKey(1L); ``` 使用通用mapper的查询所有数据方法,代码如下: ``` List<User> userList = userMapper.selectAll(); ``` 使用通用mapper的条件查询方法,代码如下: ``` Condition condition = new Condition(User.class); condition.createCriteria().andEqualTo("username", "testUser"); List<User> userList = userMapper.selectByExample(condition); ``` 以上就是使用Mybatis通用mapper的一些常用方法,它们都能够简化我们的开发工作。当然,如果有需要,我们还可以自己封装一些方法来实现更加灵活和高效的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值