Spring Boot整合Mybatis

本文介绍如何在SpringBoot项目中配置并使用MyBatis框架。通过具体步骤展示了数据库连接配置、实体类创建、业务层及Controller层的实现过程,并最终通过HTTP请求展示查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个Spring Boot项目 ,选择需要的依赖


运行一下启动应用类发现控制台打印:



我们需要配置一下数据库和Mybatis

server:
  port: 8099
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&&characterEncoding=utf8
    username: root
    password: aaaaaa
mybatis:
  type-aliases-package: com.wya.springboot.entity
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations:
  - classpath:mybatis/mapper/*.xml
  

创建如下所示目录


mapper-locations指定的是mapper.xml的位置

mybatis-config.xml是mybatis基础的配置,你也可以再写一些其他的

<typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>

然后创建实体类、业务层、Controller层


启动应用类加上MapperScan注解,用这个注解可以注册 Mybatis mapper 接口类。当然你也可以在Dao接口上加Mapper注解,不过这样太麻烦,每个接口都要加所以还是用这种方式。

package com.wya.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.wya.springboot.dao")
public class SpringbootMybatisApplication {

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

Controller层

package com.wya.springboot.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wya.springboot.entity.Student;
import com.wya.springboot.service.StudentService;

@RestController
public class StudentController {

	@Resource
	private StudentService studentService;
	
	@GetMapping("student")
	public List<Student> findAll(){
		return this.studentService.findAll();
	}
	
}

启动项目,请求一下http://localhost:8099/student



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值