SpringBoot(二)SpringBoot集成Mybatis

一、工程结构:

 

二、主要文件配置说明

1、pom.xml

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
        
<!-- 继承mybatis   启动时回默认加载src/main/resources下面的application.yml配置文件,加载数据源 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
        
<!-- 数据库连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.0</version>
</dependency>
</dependencies>


2、Application注解
   
    SpringBootApplication= (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan
    1)、@Configuration:提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。
    2)、@EnableAutoConfiguration:能够自动配置spring的上下文,试图猜测和配置你想要的bean类,通常会自动根据你的类路径和你的bean定义自动配置。
    3)、@ComponentScan:会自动扫描指定包(默认当前包及其子包)下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。


3、默认加载配置文件:src/main/resources/applcation.yml
    spring.profiles.active = dev/pro/test  开发、生产、测试环境  
    mybatis:
      mapperLocations: classpath:mapper/*.xml    #

    spring:
      profiles: dev
      datasource:
      url: jdbc:mysql://localhost:3306/test
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
      # 使用druid数据源

      type: com.alibaba.druid.pool.DruidDataSource

 

三、主要代码层说明

1)dao层:

2)service层

3)web层

4)application

5)application.yml

6)UserMapper.xml

7)pom.xml

 

Spring Boot 是一个开源的 Java 开发框架,而 MyBatis-Plus 是一个基于 MyBatis 的增强工具库。MyBatis-Plus 提供了很多便捷的功能,使得与数据库的交互更加简单和高效。 要集成 Spring Boot 和 MyBatis-Plus,可以按照以下步骤进行: 1. 添加依赖:在项目的 pom.xml 文件中添加 Spring Boot 和 MyBatis-Plus 的依赖。通常可以在 Maven 中央仓库找到它们的最新版本。 2. 配置数据源:在 application.properties 或 application.yml 文件中配置数据库连接信息,包括数据库 URL、用户名、密码等。 3. 创建实体:根据需要创建与数据库表相对应的实体。可以使用注解来标识实体与数据表的映射关系。 4. 创建 Mapper 接口:创建与实体对应的 Mapper 接口,用于定义数据库操作的方法。可以使用 MyBatis-Plus 提供的通用 CRUD 方法,也可以根据需求自定义方法。 5. 创建 Service :创建 Service ,用于封装业务逻辑并调用 Mapper 接口中的方法。可以使用注解来标识 Service 的角色,如 @Service。 6. 配置文件:在 Spring Boot 的配置中配置 MyBatis-Plus 的相关配置。可以设置数据源、Mapper 扫描路径等。 7. 启动应用程序:根据需要,可以创建一个启动并添加 @SpringBootApplication 注解。使用 Spring Boot 提供的内嵌容器启动应用程序。 通过以上步骤,就可以完成 Spring Boot 和 MyBatis-Plus 的集成。使用 MyBatis-Plus 提供的丰富功能,可以简化数据库操作,提高开发效率。这个集成方案可以在大多数使用 Spring Boot 的项目中使用,使得与数据库的交互更加方便。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值