博客
关于我
SpringBoot(十四)整合MyBatis
阅读量:796 次
发布时间:2023-02-27

本文共 5440 字,大约阅读时间需要 18 分钟。

MyBatis项目集成与数据库操作

本文将详细介绍如何使用MyBatis进行项目开发,包括数据库连接配置、实体类创建、Mapper接口编写以及相关的数据库操作实现。

一、安装必要的依赖

首先,我们需要在项目中引入MyBatis相关的依赖。通过Maven进行依赖管理,可以确保所有必要的jar包被正确引入。以下是MyBatis的核心依赖:

org.mybatis.springboot
mybatis-spring-boot-starter
2.1.1

确保项目中已经配置了上述依赖,接下来我们将进入数据库配置的步骤。

二、数据库连接配置

MyBatis在Spring Boot项目中通过数据源配置来管理数据库连接。配置文件中需要明确指定数据库连接的详细信息,包括用户名、密码、URL、驱动类以及连接池参数等。以下是常用的数据库配置示例:

spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 初始化连接池
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
# 数据库监控配置
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
# 定义监控统计拦截器
spring.datasource.filters=stat,wall,log4j

在实际应用中,根据数据库的实际情况调整上述配置参数,确保与数据库服务器兼容。

三、创建实体类

在项目中创建对应的实体类,通常使用Lombok框架简化代码编写。以下是一个简单的实体类示例:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}

该类使用了Lombok的@Data注解,简化了getter、setter和toString、hashCode方法的编写。

四、创建Mapper接口

MyBatis的核心是通过Mapper接口定义数据库操作逻辑。以下是一个简单的部门Mapper接口:

@Mapper
@Repository
public interface DepartmentMapper {
List
getDepartments();
Department getDepartment(Integer id);
}

该接口定义了两个方法:getDepartments()用于获取所有部门信息,getDepartment()用于通过部门ID获取单个部门信息。

五、Mapper映射文件

在项目的mapper目录下创建对应的XML映射文件。以下是一个简单的部门Mapper映射文件:

该文件定义了两个SQL语句:getDepartments用于查询所有部门信息,getDepartment用于通过ID查询单个部门信息。

六、资源过滤配置

为了确保项目中只编译必要的资源文件,Maven的资源过滤功能非常有用。以下是常用的资源过滤配置:

src/main/java
**/*.xml
true

该配置意味着Maven会对src/main/java目录下的所有XML文件进行编译和过滤,排除其他文件类型。

七、创建控制器进行测试

在Spring Boot项目中,控制器类用于管理HTTP请求并调用业务逻辑。以下是一个简单的部门控制器类:

@RestController
public class DepartmentController {
@Autowired
private DepartmentMapper departmentMapper;
@GetMapping("/getDepartments")
public List
getDepartments() {
return departmentMapper.getDepartments();
}
@GetMapping("/getDepartment/{id}")
public Department getDepartment(@PathVariable("id") Integer id) {
return departmentMapper.getDepartment(id);
}
}

该控制器类提供了两个HTTP端点:/getDepartments用于获取所有部门信息,/getDepartment/{id}用于通过ID获取单个部门信息。

八、增加员工类进行测试

为了验证数据库操作的完整性,我们可以在项目中创建一个员工类,并定义相应的Mapper接口和控制器类。

1、创建员工实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender; // 1代表男性,0代表女性
private Integer department;
private Date birth;
private Department eDepartment; // 偶然设计,用于关联部门信息
}

2、创建员工Mapper接口

@Mapper
@Repository
public interface EmployeeMapper {
List
getEmployees();
int save(Employee employee);
Employee get(Integer id);
int delete(Integer id);
}

3、创建员工Mapper映射文件

insert into employee (last_name, email, gender, department, birth) values (#{lastName}, #{email}, #{gender}, #{department}, #{birth});
delete from employee where id = #{id}

4、创建员工控制器类

@RestController
public class EmployeeController {
@Autowired
private EmployeeMapper employeeMapper;
@GetMapping("/getEmployees")
public List
getEmployees() {
return employeeMapper.getEmployees();
}
@GetMapping("/save")
public int save() {
Employee employee = new Employee();
employee.setLastName("zhangsan");
employee.setEmail("zhangsan@qq.com");
employee.setGender(1);
employee.setDepartment(101);
employee.setBirth(new Date());
return employeeMapper.save(employee);
}
@GetMapping("/get/{id}")
public Employee get(@PathVariable("id") Integer id) {
return employeeMapper.get(id);
}
@GetMapping("/delete/{id}")
public int delete(@PathVariable("id") Integer id) {
return employeeMapper.delete(id);
}
}

九、项目启动与测试

在IDE中启动项目后,通过浏览器访问项目的端口地址,例如http://localhost:8080,然后根据控制器提供的端点进行测试:

  • http://localhost:8080/getDepartments - 获取所有部门信息
  • http://localhost:8080/getDepartment/1 - 获取ID为1的部门信息
  • http://localhost:8080/getEmployees - 获取所有员工信息
  • http://localhost:8080/save - 新增一个员工
  • http://localhost:8080/get/1 - 获取ID为1的员工信息
  • http://localhost:8080/delete/1 - 删除ID为1的员工信息

十、总结

通过以上步骤,我们已经完成了一个基于MyBatis的全栈项目开发。从数据库连接配置到实体类创建,再到Mapper接口和控制器类的编写,每一步都需要细致的配置和测试。通过本文的详细说明,读者可以轻松地完成一个基本的MyBatis项目开发,熟悉其相关的配置和使用方法。

转载地址:http://vlvfk.baihongyu.com/

你可能感兴趣的文章
SQL-CLR 类型映射 (LINQ to SQL)
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
Orleans框架------基于Actor模型生成分布式Id
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>
os.environ 没有设置环境变量
查看>>
os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
查看>>
os.removexattr 的 Python 文档——‘*‘(星号)参数是什么意思?
查看>>
os.system 在 Python 中不起作用
查看>>
OS2ATC2017:阿里研究员林昊畅谈操作系统创新与挑战
查看>>
OSCACHE介绍
查看>>
SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
查看>>
OSChina 周五乱弹 ——吹牛扯淡的耽误你们学习进步了
查看>>