基于SpringBoot2.X整合Mybatis

有两种方式:

  •         ----注解版

  •         ----配置文件版

@注解版

新增依赖:

<dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>2.1.2</version>
</dependency>

经典全局配置文件:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: 123456

 

准备实体类:


public class Department {

	private Integer id;
	private String departmentName;

    //省略构造器,get/set方法,省略toString方法
}

mapper层接口: 举例如下

//指定这是一个操作数据库的mapper
/*可以使用mapper的批量扫描注解 ,写在启动类上*/
//@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id") //自动生成主键  并且指定对应属性
    @Insert("insert into department(department_name) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set department_name=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

controller层:

@RestController
public class DeptController {
    @Autowired
    private  DepartmentMapper departmentMapper;

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id) {
        return departmentMapper.getDeptById(id);
    }

    @GetMapping("/dept")
    public Department insertDept(Department department) {
        departmentMapper.insertDept(department);
        return department;
    }
}

 数据库的命名:

Java实体类的命名:

由于数据库的命名规范和Java不统一,所有需要始终驼峰命名配置

@Configuration
public class MybatisConfig {
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){

        return  new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                /*配置使用驼峰命名规则*/
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

浏览器访问:

当mapper层接口较多时,可是使用@MapperScan注解加在住类上:

使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.xxx.xxx.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
	}
}

------------------------------------------------------------------------------------------

配置文件版:

文件结构   举例如下:

 

 Mybatis的全局配置文件

<?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!--设置驼峰命名映射-->
    <settings>
        <setting name= "mapUnderscoreToCamelCase" value="true"/>
    </settings>

</configuration>

xxxMapper.xml文件的配置:(很常见的那种)

<?xm1 version="1.0" encoding="UTF-8" ?>
< DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.springboot.mapper.EmployeeMapper">

    <select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>
</mapper>

为了使这两个文件生效,在application.yml中设置:

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml   #指定全局配置文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml        #指定sql映射文件的位置

之后就可以写controller层的方法了

至此完成了一个Mybatis的配置文件版

更多使用参照

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot 3(目前尚未发布正式版本,假设你说的是Spring Boot 3.0)与MyBatisPlus整合是一个常见的企业级Java应用架构选择。MyBatisPlus是基于MyBatis的简化、增强工具,它提供了一些便捷的功能如自动映射、代码生成等。 整合步骤如下: 1. **添加依赖**:首先,在你的Maven或Gradle项目中添加Spring Boot的Web和MyBatisPlus的依赖。例如,如果你使用Maven: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.x.x</version> <!-- 使用最新稳定版 --> </dependency> ``` 2. **配置数据源**:在application.properties或application.yml文件中配置数据库连接信息,比如JPA的hibernate.ddl-auto属性可以设置为`update`,以便在启动时更新表结构。 3. **实体类和Mapper接口**:创建对应的领域模型(Entity)类,并在MyBatisPlus中通过注解如`@Table`、`@Field`进行轻量级的数据映射。同时,生成Mapper接口,可以使用MyBatisPlus的自动生成工具。 4. **扫描路径**:在Spring Boot的配置类中,启用MyBatisPlus的自动扫描功能,指定需要扫描Mapper接口的位置。 5. **编写服务层和控制器**:在Service层处理业务逻辑,调用Mapper的方法。Controller层则负责接收请求并调用Service。 ```java @Service public class UserService { @Autowired private UserMapper userMapper; // 业务方法... } @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public Result getUser(@PathVariable Long id) { return userService.getUser(id); } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值