Java教程

SpringBoot:数据库相关之一

本文主要是介绍SpringBoot:数据库相关之一,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

定制化

为满足需求,有时需要自己定制程序。

定制化程序的常见方式:

  • 首先需要知道原理

    • SpringBoot底层帮我们注册的诸多组件,往往都使用了@ConditionalOnMissingBean,即容器中如果没有该组件那么则注册并注入。
    • 因此需要定制化则只需要我们自己将需要替换的组件注入IOC容器即可。
  • 方式

    • 修改配置文件
    • 编写自定义配置类
    • 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:数据库相关之一的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!