首页 > 其他分享 >Mybatis框架实现单表增删改查

Mybatis框架实现单表增删改查

时间:2024-12-26 22:31:47浏览次数:4  
标签:改查 public application 单表 Mybatis import com id TravelApplication

一 数据库准备
在 MySQL 数据库中创建travel_application表:
CREATE TABLE travel_application (
ID varchar(8) NOT NULL,
name varchar(255) DEFAULT NULL,
department varchar(255) DEFAULT NULL,
destination varchar(255) DEFAULT NULL,
departuredate date DEFAULT NULL,
returndate date DEFAULT NULL,
Type varchar(255) DEFAULT NULL,
Typecontent varchar(255) DEFAULT NULL,
Reason varchar(255) DEFAULT NULL,
State varchar(255) DEFAULT NULL,
Statereason varchar(255) DEFAULT NULL,
PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
2. 创建 Spring Boot 项目
在 IDEA 中创建一个 Spring Boot 项目,选择Web和MyBatis Framework依赖。
3. 持久层(Dao)
实体类(Entity):在com.example.entity包下创建TravelApplication实体类。
package com.example.entity;

import java.util.Date;

public class TravelApplication {
private String id;
private String name;
private String department;
private String destination;
private Date departuredate;
private Date returndate;
private String type;
private String typecontent;
private String reason;
private String state;
private String statereason;

// 生成 Getter 和 Setter 方法
//...

}
Mapper 接口(Dao):在com.example.dao包下创建TravelApplicationMapper接口。
package com.example.dao;

import com.example.entity.TravelApplication;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface TravelApplicationMapper {
// 插入出差申请
@Insert("INSERT INTO travel_application (ID, name, department, destination, departuredate, returndate, Type, Typecontent, Reason, State) VALUES (#{id}, #{name}, #{department}, #{destination}, #{departuredate}, #{returndate}, #{type}, #{typecontent}, #{reason}, #{state})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insertTravelApplication(TravelApplication application);

// 根据ID删除出差申请
@Delete("DELETE FROM travel_application WHERE ID = #{id}")
void deleteTravelApplication(String id);

// 更新出差申请
@Update("UPDATE travel_application SET destination = #{destination}, departuredate = #{departuredate}, returndate = #{returndate}, Type = #{type}, Typecontent = #{typecontent}, Reason = #{reason}, State = #{state} WHERE ID = #{id}")
void updateTravelApplication(TravelApplication application);

// 查询所有出差申请
@Select("SELECT * FROM travel_application")
List<TravelApplication> selectAllTravelApplications();

// 根据条件查询出差申请
@Select("<script>SELECT * FROM travel_application WHERE 1=1 " +
        "<if test='name!= null and name!= \"\"'> AND name = #{name} </if>" +
        "<if test='department!= null and department!= \"\"'> AND department = #{department} </if>" +
        "<if test='state!= null and state!= \"\"'> AND State = #{state} </if>" +
        "</script>")
List<TravelApplication> selectTravelApplicationsByCondition(TravelApplication application);

}
Mapper XML 文件:在src/main/resources/mapper目录下创建TravelApplicationMapper.xml文件。

4. 业务层(Service) 在com.example.service包下创建TravelApplicationService类。 package com.example.service;

import com.example.dao.TravelApplicationMapper;
import com.example.entity.TravelApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TravelApplicationService {
@Autowired
private TravelApplicationMapper travelApplicationMapper;

public void insertTravelApplication(TravelApplication application) {
    travelApplicationMapper.insertTravelApplication(application);
}

public void deleteTravelApplication(String id) {
    travelApplicationMapper.deleteTravelApplication(id);
}

public void updateTravelApplication(TravelApplication application) {
    travelApplicationMapper.updateTravelApplication(application);
}

public List<TravelApplication> selectAllTravelApplications() {
    return travelApplicationMapper.selectAllTravelApplications();
}

public List<TravelApplication> selectTravelApplicationsByCondition(TravelApplication application) {
    return travelApplicationMapper.selectTravelApplicationsByCondition(application);
}

}
5. 控制层(Controller)
在com.example.controller包下创建TravelApplicationController类。
package com.example.controller;

import com.example.entity.TravelApplication;
import com.example.service.TravelApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/travel")
public class TravelApplicationController {
@Autowired
private TravelApplicationService travelApplicationService;

@PostMapping("/apply")
public void insertTravelApplication(@RequestBody TravelApplication application) {
    travelApplicationService.insertTravelApplication(application);
}

@DeleteMapping("/{id}")
public void deleteTravelApplication(@PathVariable("id") String id) {
    travelApplicationService.deleteTravelApplication(id);
}

@PutMapping("/update")
public void updateTravelApplication(@RequestBody TravelApplication application) {
    travelApplicationService.updateTravelApplication(application);
}

@GetMapping("/all")
public List<TravelApplication> selectAllTravelApplications() {
    return travelApplicationService.selectAllTravelApplications();
}

@GetMapping("/condition")
public List<TravelApplication> selectTravelApplicationsByCondition(TravelApplication application) {
    return travelApplicationService.selectTravelApplicationsByCondition(application);
}

}
6. HTML 页面
在src/main/resources/static目录下创建index.html页面。

Travel Application

Travel Application Management

<div id="result"></div>

<script>
    function getAll() {
        $.ajax({
            type: "GET",
            url: "/travel/all",
            success: function (data) {
                let resultDiv = $("#result");
                resultDiv.empty();
                data.forEach(function (app) {
                    resultDiv.append("<p>ID: " + app.id + ", Name: " + app.name + "</p>");
                });
            }
        });
    }

    function getByCondition() {
        let condition = {
            name: "John",
            department: "IT"
        };
        $.ajax({
            type: "GET",
            url: "/travel/condition",
            data: condition,
            success: function (data) {
                let resultDiv = $("#result");
                resultDiv.empty();
                data.forEach(function (app) {
                    resultDiv.append("<p>ID: " + app.id + ", Name: " + app.name + "</p>");
                });
            }
        });
    }

    function add() {
        let application = {
            id: "20230001",
            name: "Alice",
            department: "HR",
            destination: "New York",
            departuredate: "2023-01-01",
            returndate: "2023-01-05",
            type: "Business Trip",
            state: "Pending"
        };
        $.ajax({
            type: "POST",
            url: "/travel/apply",
            contentType: "application/json",
            data: JSON.stringify(application),
            success: function () {
                alert("Application added successfully");
            }
        });
    }

    function update() {
        let application = {
            id: "20230001",
            destination: "Los Angeles"
        };
        $.ajax({
            type: "PUT",
            url: "/travel/update",
            contentType: "application/json",
            data: JSON.stringify(application),
            success: function () {
                alert("Application updated successfully");
            }
        });
    }

    function deleteApp() {
        let id = "20230001";
        $.ajax({
            type: "DELETE",
            url: "/travel/" + id,
            success: function () {
                alert("Application deleted successfully");
            }
        });
    }
</script>
7. 配置文件 application.properties(在src/main/resources目录下)配置如下: spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name spring.datasource.username=your_username spring.datasource.password=your_password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver mybatis.mapper-locations=classpath:mapper/*.xml

标签:改查,public,application,单表,Mybatis,import,com,id,TravelApplication
From: https://www.cnblogs.com/yololin/p/18634323

相关文章

  • 告别数据库小白:MyBatis让你秒变数据库操作达人!
    Whitegraces:个人主页......
  • Mybatis-Plus基础
    这里写目录标题MyBatisPlus基础1.MyBatisPlus使用1.1引入MyBatisPlus依赖1.2Mapper接口继承BaseMapper<T>1.3测试2.MyBatisPlus注解2.1常见注解2.2IdType枚举2.3@TableField使用场景3.MyBatisPlus配置4.核心功能4.1条件构造器4.1.1基于QueryWrapper查询4.1......
  • Mybatis-Plus实现多租户数据隔离
    上篇文章中已经介绍了实现mybatisPlus多租户的最简单的方式,但逻辑也比较单一,只有多租户的基础功能这个多租户plus版本在原来的基础功能上做了一些功能的集成1.通过配置来控制多租户功能的启用2.通过配置来指定多租户字段3.通过配置来排除需要走多租户逻辑的表4.通过扫......
  • mybatis 连接 ORACLE
    mybatis连接ORACLE|Id|Title|DateAdded|SourceUrl|PostType|Body|BlogId|Description|DateUpdated|IsMarkdown|EntryName|CreatedTime|IsActive|AutoDesc|AccessPermission||-------------|-------------|-------------|-------------|--......
  • mybatis generatorConfiguration 生成代码
    mybatisgeneratorConfiguration生成代码|Id|Title|DateAdded|SourceUrl|PostType|Body|BlogId|Description|DateUpdated|IsMarkdown|EntryName|CreatedTime|IsActive|AutoDesc|AccessPermission||-------------|-------------|-------------|......
  • mybatis入门
    一、Mybatis的简介mybatis封装了jdbc的持久层框架,前身为ibatis,在配置文件中编写sql,是不完全orm映射框架。查看百度百科的介绍1、支持普通sql查询2、高级映射3、存储过程......
  • mybatis完成联表查询结果的封装。
    1.mybatis完成联表查询结果的封装。表与表之间通过外键会建立关联关系。我们也可以通过联表查询得到多张表的数据。我们java中如何通过实体类建立这种关系呢?例如:班级表1-----n学生表(外键列)。查询学生信息时要求携带班级信息。一定使用了联表查询的sql语句.select*fro......
  • mybatis动态sql标签
    根据条件--sql发生改变。需要使用mybatis的动态sql标签作用这些动态SQL标签在MyBatis中提供了灵活的查询和更新操作的能力,可以根据不同的条件动态生成SQL语句,使SQL映射文件更具可读性和可维护性。常见的mybatis动态sql标签<trim>:通过修剪SQL语句的开头和结尾来动态......
  • mybatis(2)
    1.注解模式--了解之前我们使用mybatis完成数据库表操作时,使用的是xml映射文件来完成。我们也可以使用主键模式完成对表的操作。dao接口配置文件2.mybatis的优化2.1添加sql日志文件我们刚才操作数据库表时,没有再控制台打印sql语句,添加日志文件后,即可再控制台打印sql语......
  • mybatis
    1.什么是mybatis框架?MyBatis是一款优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射。MyBatis免除了几乎所有的JDBC代码以及设置参数和获取结果集的工作。MyBatis可以通过简单的XML或注解来配置和映射实体类型、接口和JavaPOJO(PlainOldJavaObjects,普通老式......