当前位置:   article > 正文

SpringBoot整合mybatis实现增删改查_springbootmybatis增删改查

springbootmybatis增删改查

步骤:
1、创建项目;
2、添加mybatis依赖
3、在application.yml进行数据源属性配置;
4、定义数据源对象与配置文件中前缀是spring.datasource的配置进行绑定;
5、创建数据表(department,employee);
6、创建实体类;
7、创建mapper接口;
8、编写controller处理请求,调用mapper对象执行查询方法。

1.创建项目

项目结构:

2,添加Druid依赖

  1. <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid</artifactId>
  5. <version>1.1.10</version>
  6. </dependency>

application.yml

  1. #端口号
  2. server:
  3. port: 8080
  4. #数据源配置
  5. spring:
  6. datasource:
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. url: jdbc:mysql://localhost:3306/myjdbc212?characterEncoding=utf-8&serverTimezone=UTC
  9. username: root
  10. password: 123456
  11. #sql:
  12. #init:
  13. #指定脚本文件位置
  14. #schema-locations: classpath:user.sql
  15. #初始化方式
  16. #mode: always
  17. #设置数据源类型C
  18. type: com.alibaba.druid.pool.DruidDataSource
  19. mybatis:
  20. configuration:
  21. map-underscore-to-camel-case: true
  22. #mybatis:
  23. #指定mybatis配置文件的位置
  24. #config-location: classpath:mybatis/mybatis-config.xml
  25. #指定映射文件的位置
  26. mapper-locations: classpath:mybatis/mapper/*.xml

3,config包下

DruidConfig类

  1. @Configuration
  2. public class DruidConfig {
  3. @ConfigurationProperties(prefix = "spring.datasource")
  4. @Bean
  5. public DruidDataSource getDurid(){
  6. return new DruidDataSource();
  7. }
  8. }

MyBatisConfig类

  1. @Configuration
  2. public class MyBatisConfig {
  3. public ConfigurationCustomizer configurationCustomizer(){
  4. return new ConfigurationCustomizer() {
  5. @Override
  6. public void customize(org.apache.ibatis.session.Configuration configuration) {
  7. //下划线与驼峰命名进行自动映射
  8. configuration.setMapUnderscoreToCamelCase(true);
  9. }
  10. };
  11. }
  12. }

4,controller类

DepartmentController类:

  1. @RestController
  2. public class DepartmentController {
  3. @Autowired
  4. private DepartmentMapper departmentMapper;
  5. //根据id查询部门
  6. @RequestMapping("/dept/{id}")
  7. public Department getDepById(@PathVariable("id") Integer deptId){
  8. //调用mapper接口中的方法
  9. Department deptById = departmentMapper.getDeptById(deptId);
  10. return deptById;
  11. }
  12. //添加
  13. @RequestMapping("/dept")
  14. public int addDept(Department department){
  15. int count = departmentMapper.insertDept(department);
  16. return count;
  17. }
  18. @RequestMapping("/update/dept/{id}")
  19. public int update(Department department){
  20. int count = departmentMapper.updateDept(department);
  21. return count;
  22. }
  23. @RequestMapping("/delete/dept/{id}")
  24. public int deleteDept(@PathVariable("id")Integer id){
  25. int count = departmentMapper.deleteDept(id);
  26. return count;
  27. }
  28. }

EmpController类

  1. @RestController
  2. public class EmpController {
  3. @Autowired
  4. private EmployeeMapper employeeMapper;
  5. @RequestMapping("/emp/{id}")
  6. public Employee getEmpById(@PathVariable("id") Integer empId){
  7. Employee employee = employeeMapper.queryEmpById(empId);
  8. return employee;
  9. }
  10. @RequestMapping("/emp")
  11. public int insertEmp(Employee employee){
  12. int count = employeeMapper.insertEmp(employee);
  13. return count;
  14. }
  15. @RequestMapping("/emp/update/{id}")
  16. public int update(Employee employee,@PathVariable("id") Integer id){
  17. int count = employeeMapper.update(employee, id);
  18. return count;
  19. }
  20. @RequestMapping("/emp/delete/{id}")
  21. public int deleteEmp(@PathVariable("id")Integer id){
  22. int count = employeeMapper.deleteEmpById(id);
  23. return count;
  24. }

5,实体类entity:

Department类:

  1. package com.dzqc.entity;
  2. public class Department {
  3. private Integer id;
  4. private String departmentName;
  5. public Department() {
  6. }
  7. public Department(int i, String string) {
  8. this.id = i;
  9. this.departmentName = string;
  10. }
  11. public Integer getId() {
  12. return id;
  13. }
  14. public void setId(Integer id) {
  15. this.id = id;
  16. }
  17. public String getDepartmentName() {
  18. return departmentName;
  19. }
  20. public void setDepartmentName(String departmentName) {
  21. this.departmentName = departmentName;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Department [id=" + id + ", departmentName=" + departmentName + "]";
  26. }
  27. }

Employee类:

  1. package com.dzqc.entity;
  2. import java.util.Date;
  3. public class Employee {
  4. private Integer id;
  5. private String lastName;
  6. private String email;
  7. //1 male, 0 female
  8. private Integer gender;
  9. private Department department;
  10. public Employee() {
  11. }
  12. public Employee(Integer id, String lastName, String email, Integer gender, Department department, Integer did) {
  13. this.id = id;
  14. this.lastName = lastName;
  15. this.email = email;
  16. this.gender = gender;
  17. this.department = department;
  18. }
  19. public Integer getId() {
  20. return id;
  21. }
  22. public void setId(Integer id) {
  23. this.id = id;
  24. }
  25. public String getLastName() {
  26. return lastName;
  27. }
  28. public void setLastName(String lastName) {
  29. this.lastName = lastName;
  30. }
  31. public String getEmail() {
  32. return email;
  33. }
  34. public void setEmail(String email) {
  35. this.email = email;
  36. }
  37. public Integer getGender() {
  38. return gender;
  39. }
  40. public void setGender(Integer gender) {
  41. this.gender = gender;
  42. }
  43. public Department getDepartment() {
  44. return department;
  45. }
  46. public void setDepartment(Department department) {
  47. this.department = department;
  48. }
  49. @Override
  50. public String toString() {
  51. return "Employee{" +
  52. "id=" + id +
  53. ", lastName='" + lastName + '\'' +
  54. ", email='" + email + '\'' +
  55. ", gender=" + gender +
  56. ", department=" + department +
  57. '}';
  58. }
  59. }

6,mapper包下

DepartmentMapper:

  1. package com.dzqc.mapper;
  2. import com.dzqc.entity.Department;
  3. import org.apache.ibatis.annotations.Insert;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.Select;
  6. import org.apache.ibatis.annotations.Update;
  7. import org.springframework.stereotype.Repository;
  8. //可以在mapper接口中使用注解编写sql语句,访问数据库进行操作
  9. //可以在启动类前使用@MapperScane扫描指定包下所有的mapper接口
  10. @Mapper
  11. @Repository
  12. public interface DepartmentMapper {
  13. //根据id查询部门
  14. @Select("select*from department where id=#{deptId}")
  15. public Department getDeptById(Integer deptId);
  16. //插入部门
  17. @Insert("insert into department(department_name) values(#{departmentName})")
  18. public int insertDept(Department department);
  19. //更新
  20. @Update("update department set department_name=#{departmentName} where id=#{id}")
  21. public int updateDept(Department department);
  22. //删除
  23. @Update("delete from department where id=#{deptId}")
  24. public int deleteDept(Integer deptId);
  25. }

EmpoyeeMapper类:

  1. @Mapper
  2. @Repository
  3. public interface EmployeeMapper {
  4. //查询
  5. Employee queryEmpById(Integer empId);
  6. //添加
  7. int insertEmp(Employee employee);
  8. //更新
  9. int update(@PathVariable("employee") Employee employee, @Param("id") Integer id);
  10. //删除
  11. int deleteEmpById(Integer id);
  12. }

7,创建EmployeeMapper要mybatis/mapper/EmployeeMapper

EmployeeMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <!--MyBatis的映射文件 编写sql-->
  6. <!--一个数据表对应一个实体类,一个实体类对应一个mapper映射文件-->
  7. <mapper namespace="com.dzqc.mapper.EmployeeMapper">
  8. <resultMap id="EmpResultMap" type="com.dzqc.entity.Employee">
  9. <id column="id" property="id"></id>
  10. <result column="last_name" property="lastName"></result>
  11. <result column="email" property="email"></result>
  12. <result column="gender" property="gender"></result>
  13. <association property="department" javaType="com.dzqc.entity.Department">
  14. <id column="id" property="id"></id>
  15. <result column="department_name" property="departmentName"></result>
  16. </association>
  17. </resultMap>
  18. <!--Employee queryEmpById(@Param("empId") Integer id);-->
  19. <select id="queryEmpById" resultMap="EmpResultMap">
  20. select*from employee where id=#{empId}
  21. </select>
  22. <!--int insertEmp(Employee employee);-->
  23. <insert id="insertEmp">
  24. insert into employee values (#{id},#{lastName},#{email},#{gender},#{department.id})
  25. </insert>
  26. <update id="update">
  27. update employee
  28. <set>
  29. <if test="employee.lastName!=null">
  30. last_name=#{employee.lastName},
  31. </if>
  32. <if test="employee.email!=null">
  33. email=#{employee.email},
  34. </if>
  35. <if test="employee.gender!=null">
  36. gender=#{employee.gender},
  37. </if>
  38. <if test="employee.department!=null">
  39. d_id=#{employee.department.id}
  40. </if>
  41. </set>
  42. where id = #{id}
  43. </update>
  44. <!--int deleteEmpById(Integer id);-->
  45. <delete id="deleteEmpById">
  46. delete from employee where id=#{id}
  47. </delete>
  48. </mapper>

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <!--根标签-->
  6. <configuration>
  7. <!--全局设置-->
  8. <settings>
  9. <!--开启驼峰命名自动映射 即下划线自动映射成驼峰命名-->
  10. <setting name="mapUnderscoreToCamelCase" value="true"/>
  11. </settings>
  12. </configuration>

数据库:department

  1. /*
  2. Navicat MySQL Data Transfer
  3. Source Server : db
  4. Source Server Version : 50735
  5. Source Host : localhost:3306
  6. Source Database : myjdbc212
  7. Target Server Type : MYSQL
  8. Target Server Version : 50735
  9. File Encoding : 65001
  10. Date: 2023-04-23 16:06:49
  11. */
  12. SET FOREIGN_KEY_CHECKS=0;
  13. -- ----------------------------
  14. -- Table structure for department
  15. -- ----------------------------
  16. DROP TABLE IF EXISTS `department`;
  17. CREATE TABLE `department` (
  18. `id` int(11) NOT NULL AUTO_INCREMENT,
  19. `department_name` varchar(255) DEFAULT NULL,
  20. PRIMARY KEY (`id`)
  21. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
  22. -- ----------------------------
  23. -- Records of department
  24. -- ----------------------------
  25. INSERT INTO `department` VALUES ('1', 'A');
  26. INSERT INTO `department` VALUES ('3', 'E');
  27. INSERT INTO `department` VALUES ('4', null);

employee

  1. /*
  2. Navicat MySQL Data Transfer
  3. Source Server : db
  4. Source Server Version : 50735
  5. Source Host : localhost:3306
  6. Source Database : myjdbc212
  7. Target Server Type : MYSQL
  8. Target Server Version : 50735
  9. File Encoding : 65001
  10. Date: 2023-04-13 16:02:30
  11. */
  12. SET FOREIGN_KEY_CHECKS=0;
  13. -- ----------------------------
  14. -- Table structure for employee
  15. -- ----------------------------
  16. DROP TABLE IF EXISTS `employee`;
  17. CREATE TABLE `employee` (
  18. `id` int(11) NOT NULL AUTO_INCREMENT,
  19. `last_name` varchar(255) DEFAULT NULL,
  20. `email` varchar(255) DEFAULT NULL,
  21. `gender` int(2) DEFAULT NULL,
  22. `birth` date DEFAULT NULL,
  23. `d_id` int(11) DEFAULT NULL,
  24. PRIMARY KEY (`id`)
  25. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  26. -- ----------------------------
  27. -- Records of employee
  28. -- ----------------------------

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/232852
推荐阅读
相关标签
  

闽ICP备14008679号