国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術文章
文章詳情頁

SpringBoot+Mybatis使用Mapper接口注冊的幾種方式

瀏覽:82日期:2023-02-25 16:48:50
目錄I. 環境準備1. 數據庫準備2. 項目環境II. 實例演示1. 實體類,Mapper類2. 注冊方式2.1 @MapperScan注冊方式2.2 @Mapper 注冊方式2.3 MapperScannerConfigurer注冊方式3. 小結III. 不能錯過的源碼和相關知識點

SpringBoot項目中借助Mybatis來操作數據庫,對大部分java技術棧的小伙伴來說,并不會陌生;我們知道,使用mybatis,一般會有下面幾個

Entity: 數據庫實體類 Mapper: db操作接口 Service: 服務類 xml文件:寫sql的地方

本篇博文中主要介紹是Mapper接口與對應的xml文件如何關聯的幾種姿勢(這個問題像不像'茴'字有幾個寫法😬)

I. 環境準備1. 數據庫準備

使用mysql作為本文的實例數據庫,新增一張表

CREATE TABLE `money` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT ’’ COMMENT ’用戶名’, `money` int(26) NOT NULL DEFAULT ’0’ COMMENT ’錢’, `is_deleted` tinyint(1) NOT NULL DEFAULT ’0’, `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ’創建時間’, `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ’更新時間’, PRIMARY KEY (`id`), KEY `name` (`name`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;2. 項目環境

本文借助 SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA進行開發

pom依賴如下

<dependencies> <dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version> </dependency> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId> </dependency></dependencies>

db配置信息 application.yml

spring: datasource: url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password:II. 實例演示

前面基礎環境搭建完成,接下來準備下Mybatis的Entity,Mapper等基礎類

1. 實體類,Mapper類

數據庫實體類MoneyPo

@Datapublic class MoneyPo { private Integer id; private String name; private Long money; private Integer isDeleted; private Timestamp createAt; private Timestamp updateAt;}

對應的Mapper接口(這里直接使用注解的方式來實現CURD)

public interface MoneyMapper { /** * 保存數據,并保存主鍵id * * @param po * @return int */ @Options(useGeneratedKeys = true, keyProperty = 'po.id', keyColumn = 'id') @Insert('insert into money (name, money, is_deleted) values (#{po.name}, #{po.money}, #{po.isDeleted})') int save(@Param('po') MoneyPo po); /** * 更新 * * @param id id * @param money 錢 * @return int */ @Update('update money set `money`=#{money} where id = #{id}') int update(@Param('id') int id, @Param('money') long money); /** * 刪除數據 * * @param id id * @return int */ @Delete('delete from money where id = #{id}') int delete(@Param('id') int id); /** * 主鍵查詢 * * @param id id * @return {@link MoneyPo} */ @Select('select * from money where id = #{id}') @Results(id = 'moneyResultMap', value = { @Result(property = 'id', column = 'id', id = true, jdbcType = JdbcType.INTEGER), @Result(property = 'name', column = 'name', jdbcType = JdbcType.VARCHAR), @Result(property = 'money', column = 'money', jdbcType = JdbcType.INTEGER), @Result(property = 'isDeleted', column = 'is_deleted', jdbcType = JdbcType.TINYINT), @Result(property = 'createAt', column = 'create_at', jdbcType = JdbcType.TIMESTAMP), @Result(property = 'updateAt', column = 'update_at', jdbcType = JdbcType.TIMESTAMP)}) MoneyPo getById(@Param('id') int id);}

對應的Service類

@Slf4j@Servicepublic class MoneyService { @Autowired private MoneyMapper moneyMapper; public void basicTest() {int id = save();log.info('save {}', getById(id));boolean update = update(id, 202L);log.info('update {}, {}', update, getById(id));boolean delete = delete(id);log.info('delete {}, {}', delete, getById(id)); } private int save() {MoneyPo po = new MoneyPo();po.setName('一灰灰blog');po.setMoney(101L);po.setIsDeleted(0);moneyMapper.save(po);return po.getId(); } private boolean update(int id, long newMoney) {int ans = moneyMapper.update(id, newMoney);return ans > 0; } private boolean delete(int id) {return moneyMapper.delete(id) > 0; } private MoneyPo getById(int id) {return moneyMapper.getById(id); }}2. 注冊方式

注意,上面寫完之后,若不通過下面的幾種方式注冊Mapper接口,項目啟動會失敗,提示找不到MoneyMapper對應的bean

Field moneyMapper in com.git.hui.boot.mybatis.service.MoneyService required a bean of type ’com.git.hui.boot.mybatis.mapper.MoneyMapper’ that could not be found.

2.1 @MapperScan注冊方式

在配置類or啟動類上,添加@MapperScan注解來指定Mapper接口的包路徑,從而實現Mapper接口的注冊

@MapperScan(basePackages = 'com.git.hui.boot.mybatis.mapper')@SpringBootApplicationpublic class Application { public Application(MoneyService moneyService) {moneyService.basicTest(); } public static void main(String[] args) {SpringApplication.run(Application.class); }}

執行之后輸出結果如下

2021-07-06 19:12:57.984 INFO 1876 --- [ main] c.g.h.boot.mybatis.service.MoneyService : save MoneyPo(id=557, name=一灰灰blog, money=101, isDeleted=0, createAt=2021-07-06 19:12:57.0, updateAt=2021-07-06 19:12:57.0)2021-07-06 19:12:58.011 INFO 1876 --- [ main] c.g.h.boot.mybatis.service.MoneyService : update true, MoneyPo(id=557, name=一灰灰blog, money=202, isDeleted=0, createAt=2021-07-06 19:12:57.0, updateAt=2021-07-06 19:12:57.0)2021-07-06 19:12:58.039 INFO 1876 --- [ main] c.g.h.boot.mybatis.service.MoneyService : delete true, null

注意:

basePackages: 傳入Mapper的包路徑,數組,可以傳入多個 包路徑支持正則,如com.git.hui.boot.*.mapper 上面這種方式,可以避免讓我們所有的mapper都放在一個包路徑下,從而導致閱讀不友好2.2 @Mapper 注冊方式

前面的@MapperScan指定mapper的包路徑,這個注解則直接放在Mapper接口上

@Mapperpublic interface MoneyMapper {...}

測試輸出省略...

2.3 MapperScannerConfigurer注冊方式

使用MapperScannerConfigurer來實現mapper接口注冊,在很久以前,還是使用Spring的xml進行bean的聲明的時候,mybatis的mapper就是這么玩的

<bean class='org.mybatis.spring.mapper.MapperScannerConfigurer'><property name='basePackage' value='xxx'/><property name='sqlSessionFactoryBeanName' value='sqlSessionFactory'/></bean>

對應的java代碼如下:

@Configurationpublic class AutoConfig { @Bean(name = 'sqlSessionFactory') public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(// 設置mybatis的xml所在位置,這里使用mybatis注解方式,沒有配置xml文件new PathMatchingResourcePatternResolver().getResources('classpath*:mapping/*.xml'));return bean.getObject(); } @Bean('sqlSessionTemplate') public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory storySqlSessionFactory) {return new SqlSessionTemplate(storySqlSessionFactory); } @Bean public MapperScannerConfigurer mapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage('com.git.hui.boot.mybatis.mapper');mapperScannerConfigurer.setSqlSessionFactoryBeanName('sqlSessionFactory');mapperScannerConfigurer.setSqlSessionTemplateBeanName('sqlSessionTemplate');return mapperScannerConfigurer; }}

測試輸出省略

3. 小結

本文主要介紹Mybatis中Mapper接口的三種注冊方式,其中常見的兩種注解方式

@MapperScan: 指定Mapper接口的包路徑 @Mapper: 放在mapper接口上 MapperScannerConfigurer: 編程方式注冊

那么疑問來了,為啥要介紹這三種方式,我們實際的業務開發中,前面兩個基本上就滿足了;什么場景會用到第三種方式?

如寫通用的Mapper(類似Mybatis-Plus中的BaseMapper)如一個Mapper,多數據源的場景(如主從庫,冷熱庫,db的操作mapper一致,但是底層的數據源不同)

III. 不能錯過的源碼和相關知識點

工程:https://github.com/liuyueyi/spring-boot-demo源碼:https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/104-mybatis-ano

到此這篇關于SpringBoot+Mybatis使用Mapper接口注冊的幾種方式的文章就介紹到這了,更多相關SpringBoot Mapper接口注冊內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 亚洲三级视频在线观看 | 欧美亚洲日本国产综合网 | 国产三级香港三韩国三级 | 99爱在线精品视频网站 | 一二三区在线观看 | 中国一级特黄大片毛片 | 最近中文字幕精彩视频 | 国产成人精品午夜在线播放 | 男女性男女刺激大片免费观看 | 亚洲国产国产综合一区首页 | 欧美国产成人精品一区二区三区 | 成人高清在线观看播放 | 免费一级毛片私人影院a行 免费一级毛片无毒不卡 | 性做久久久久免费观看 | 热99re久久精品这里都是免费 | www.久草.com | 国产网站免费视频 | 91亚洲精品一区二区福利 | 大黄一级片| 亚洲美女免费视频 | 国产日韩欧美视频在线 | 欧美三级aaa | 欧美日韩一区二区视频图片 | 日韩 国产 在线 | 亚洲欧美日本国产综合在线 | 久久手机在线视频 | 一级毛片免费看 | 不卡无毒免费毛片视频观看 | 一 级做人爱全视频在线看 一本不卡 | 天天澡天天碰天天狠伊人五月 | 国产国模福利视频 | 国产免费高清在线精品一区 | 亚洲国产精品欧美日韩一区二区 | 亚洲欧美成人综合久久久 | 99福利网 | 亚洲精品美女在线观看 | 97视频在线观看免费 | 亚洲国产成人精品激情 | 天天夜夜久久 | 国产亚洲网站 | 韩国本免费一级毛片免费 |