mybatis是一個很好用的工具,但是編寫mapper是一件很麻煩的事,自mybatis 3.0開始可以使用注解的方式,極大的簡化了xml的編寫量,本地想看看mybatis源碼,自己擴展寫一個工具,在閱讀源碼過程中發現一個通用mapper的工具包,感覺不用重復造輪子了,簡要記錄一下spring boot整合通用mapper的使用。
mapper注解的主要作用,
確保可以正常使用mybatis
pom引入依賴包,starter需要配合@Mapper注解使用,這里采用這種方式,或者使用@MapperScan
注解,@tk.mybatis.spring.annotation.MapperScan(basePackages = "掃描包")
配合原生mapper使用。
<dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>{version}</version>
</dependency>
Mybatis框架,我使用的版本是2.0.2
Mybatis 掃描配置(Deprecated, spring 自動配置)
@Configuration
//TODO 注意,由于MapperScannerConfigurer執行的比較早,所以必須有下面的注解
@AutoConfigureAfter(MybatisAutoConfiguration.class)
public class MyBatisMapperScannerConfig {@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");mapperScannerConfigurer.setBasePackage("org.springboot.sample.mapper");Properties properties = new Properties();// 這里要特別注意,不要把MyMapper放到 basePackage 中,也就是不能同其他Mapper一樣被掃描到。 properties.setProperty("mappers", MyMapper.class.getName());properties.setProperty("notEmpty", "false");properties.setProperty("IDENTITY", "MYSQL");mapperScannerConfigurer.setProperties(properties);return mapperScannerConfigurer;}
}
新建BaseMapper類,該類不能被當做普通Mapper一樣被掃描 ,不加@Mapper注解,或者放在不同文件夾
package com.zj.mapper;import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;public interface BaseMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
mapper注入為null。業務處理dao層,擴展BaseMapper
package com.zj.mapper;import com.zj.model.OrderInfo;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface OrderInfoMapper extends BaseMapper<OrderInfo> {}
其他和使用普通mybatis一致,service層部分代碼
orderInfoMapper.insertSelective(info);
OrderInfo info = orderInfoMapper.selectByPrimaryKey(id);
通用mapper提供常用的一些操作方法: deleteByPrimaryKey, insert, insertSelective, selectByPrimaryKey, updateByPrimaryKeySelective, updateByPrimaryKey, insertList等很多方法,需要你進一步探索
Mybatis。主鍵id問題
當使用insert,insertSelective等方法時,希望返回由數據庫產生的逐漸,需要在實體類上增加注解
@Id
@GeneratedValue(generator = "JDBC")
private Long orderInfoId;
generator="JDBC"表示 MyBatis 使用 JDBC 的 getGeneratedKeys 方法來取出由數據庫內部生成的主鍵 ,適用于MySQL,SQL Server等的自增主鍵。
mapper,或者:
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
如果實體字段和數據庫字段不一致,可以使用@Column
注解,其他注解 參見注解
@Column(name="SCORE_SUM")private String sumScore;
MBG生成參見https://github.com/abel533/Mapper/wiki/4.1.mappergenerator,demo見 git@github.com:silloy/mybatis-generator.git
更多細節參見wiki
通用Mapper極大的簡化了xml文件的編寫,但仍需要少許xml文件,有待進一步優化。同時因為這是一個個人項目,使用不太熟悉不建議使用。
本文由 歧途老農 創作,采用 CC BY 4.0 CN 協議 進行許可。 可自由轉載、引用,但需署名作者且注明文章出處。
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态