SpringBoot:数据库相关之一
2022/2/21 19:33:36
本文主要是介绍SpringBoot:数据库相关之一,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
定制化
为满足需求,有时需要自己定制程序。
定制化程序的常见方式:
-
首先需要知道原理
- SpringBoot底层帮我们注册的诸多组件,往往都使用了
@ConditionalOnMissingBean
,即容器中如果没有该组件那么则注册并注入。 - 因此需要定制化则只需要我们自己将需要替换的组件注入IOC容器即可。
- SpringBoot底层帮我们注册的诸多组件,往往都使用了
-
方式
- 修改配置文件
- 编写自定义配置类
- web应用,实现
WebMvcConfigurer
。
@Configuration public class InterceptorConf implements WebMvcConfigurer { @Bean public WebMvcRegistrations webMvcRegistrations(){ return new WebMvcRegistrations() { @Override public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return null; } }; } }
如果想完全接管SpringMVC则需要加上
@EnableWebMVC
注解。一旦完全接管,则静态资源、欢迎页、视图解析器等自动配置失效。@EnableWebMVC
会导入DelegatingWebMvcConfiguration
,这个配置类中其实也自动配置了一些底层的东西。@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(DelegatingWebMvcConfiguration.class) public @interface EnableWebMvc { }
WebMvcAutoConfiguration
想要生效,容器中必须没有WebMvcConfigurationSupport
。而DelegatingWebMvcConfiguration
继承于WebMvcConfigurationSupport
,因此WebMvcAutoConfiguration
不会生效。总结:
@EnableWebMVC
导致WebMvcAutoConfiguration
没有生效。
数据库访问
导入JDBC场景
你只需要配置url、driver、username、password
spring: datasource: url: jdbc:mysql://localhost:3307/boerk username: root password: root123 driver-class-name: com.mysql.jdbc.Driver
谨记:是username不是data-username,是password不是data-password(别问我为什么)。
Mybatis
-
需要引入依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
-
需要指定全局配置文件位置和映射文件位置
spring: datasource: url: jdbc:mysql://localhost:3307/boerk username: root password: root123 driver-class-name: com.mysql.jdbc.Driver mybatis: config-location: classpath:mybatis/Mybatis-conf.xml mapper-locations: classpath:mybatis/mapper/*.xml
-
其他按照以往进行书写。
//controller @RequestMapping("/get/{id}") @ResponseBody public User getUserById(@PathVariable("id") int id){ User user = userService.getUserById(id); System.out.println(user); return user; } //service public User getUserById(int id){ return userMapper.getUserById(id); } //mapper User getUserById(int id);
-
提醒:必须给mapper接口标注
@mapper
注解,这样才能被mybatis扫描到。 -
由于全局配置文件中没有写任何东西,以及任何的setting都可以通过
configuration
在配置文件中设置,所有全局配置文件可以不写。且一旦使用configuration
,就不能存在全局配置文件。 -
严格来说是通过
configuration
来指定mybatis的相关配置项。
也可以使用基于注解的方式进行CRUD。
@SELECT("select * from user where uid = #{id}") User getUserById(int id); //@Options为当前CRUD标签的配置项。比如resultMap等等。
可以完全摆脱配置文件。当然也可以两种方式都使用。
使用@MapperScan("xx")
可以简化开发,设置mapper扫描路径。
这篇关于SpringBoot:数据库相关之一的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求
- 2024-10-01使用 golang 将ETH账户的资产平均分散到其他账户
- 2024-10-01JWT用户校验课程:从入门到实践
- 2024-10-01Server Component课程入门指南
- 2024-09-30Dnd-Kit学习:新手快速入门指南