目录

一、组件版本

二、实现功能

三、代码实现

1、代码结构

2、pom文件

3、核心代码

4、模版文件

四、测试结果

1、news

2、goods


一、组件版本

1)java 1.8.0_451
2)springboot 2.7.18
3)pagehelper-spring-boot-starter 1.4.5
4)mysql-connector-java


二、实现功能

1)实现界面的增删改查
2)mybatis支持sql写mapper文件和xml文件两种方式
3)pagehelper实现分页功能

三、代码实现

1、代码结构

2、pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springboot-mybatis-crud</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.18</version>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- SpringBoot Web 模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>provided</scope>
        </dependency>

        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <!-- Thymeleaf for Frontend -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- PageHelper分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.5</version> <!-- 请根据需要选择合适的版本 -->
        </dependency>

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName><!--修改编译出来的jar包名,仅为{artifactId}.jar-->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <descriptorRefs>
                        <!--给jar包起的别名-->
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>org.example.MyApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

3、核心代码

MyApplication.java
package org.example;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;

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

application.yml

spring:
  profiles:
    active: dev

application-dev.yml

server:
  port: 8081


---

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot-demo
    username: root
    password: abc123456

  # 模版配置
  thymeleaf:
    mode: HTML5
    cache: false
    encoding: UTF-8
    prefix: classpath:/templates/
    suffix: .html

# mybatis 相关配置
mybatis:
  #目的是为了省略resultType里的代码量
  type-aliases-package: org.example.pojo
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

# PageHelper 相关配置
pagehelper:
  helperDialect: mysql
  reasonable: true

controller/NewsController.java

package org.example.controller;


import org.example.pojo.News;
import org.example.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    @GetMapping("/")
    public String list(Model model) {
        List<News> newsList = newsService.getAllNews();
        model.addAttribute("newsList", newsList);
        return "news/list";
    }

    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("news", new News());
        return "news/add";
    }

    @PostMapping("/save")
    public String save(@ModelAttribute News news) {
        newsService.saveNews(news);
        return "redirect:/news/";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        News news = newsService.getNewsById(id);
        model.addAttribute("news", news);
        return "news/edit";
    }

    @PostMapping("/update")
    public String update(@ModelAttribute News news) {
        newsService.updateNews(news);
        return "redirect:/news/";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        newsService.deleteNews(id);
        return "redirect:/news/";
    }
}

controller/GoodsController.java
package org.example.controller;

import com.github.pagehelper.PageInfo;
import org.example.pojo.Goods;
import org.example.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    /**
     * 商品列表(含分页)
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @GetMapping("/")
    public String list(@RequestParam(defaultValue = "1") int pageNum,
                       @RequestParam(defaultValue = "10") int pageSize,
                       Model model) {
        List<Goods> goodsList = goodsService.getAllGoods(pageNum, pageSize);
        PageInfo<Goods> pageInfo = new PageInfo<>(goodsList);
        model.addAttribute("goodsList", goodsList);
        model.addAttribute("pageNum", pageNum);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalPages", pageInfo.getPages()); // 添加总页数
        return "goods/list";
    }

    @GetMapping("/add")
    public String add(Model model) {
        model.addAttribute("goods", new Goods());
        return "goods/add";
    }

    @PostMapping("/save")
    public String save(@ModelAttribute Goods goods) {
        goodsService.saveGoods(goods);
        return "redirect:/goods/";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        Goods goods = goodsService.getGoodsById(id);
        model.addAttribute("goods", goods);
        return "goods/edit";
    }

    @PostMapping("/update")
    public String update(@ModelAttribute Goods goods) {
        goodsService.updateGoods(goods);
        return "redirect:/goods/";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        goodsService.deleteGoods(id);
        return "redirect:/goods/";
    }
}

config/MyBatisConfig.java

package org.example.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan("org.example.mapper")
public class MyBatisConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml"));
        return sessionFactory.getObject();
    }
}

pojo/News.java

package org.example.pojo;

import java.time.LocalDateTime;

public class News {
    private Integer id;
    private String title;
    private String content;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;

    // Getters and Setters
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

    public LocalDateTime getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(LocalDateTime updatedAt) {
        this.updatedAt = updatedAt;
    }
}

pojo/Goods.java

package org.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.time.LocalDateTime;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Goods {
    private Integer id;
    private String name;
    private String description;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
}

mapper/NewsMapper.java

package org.example.mapper;


import org.apache.ibatis.annotations.*;
import org.example.pojo.News;

import java.util.List;

/**
 * 文章Mapper - sql都写在 mapper 文件中
 */
public interface NewsMapper {
    @Select("SELECT * FROM news")
    List<News> findAll();

    @Select("SELECT * FROM news WHERE id = #{id}")
    News findById(@Param("id") Integer id);

    @Insert("INSERT INTO news (title, content) VALUES (#{title}, #{content})")
    void insert(News news);

    @Update("UPDATE news SET title = #{title}, content = #{content} WHERE id = #{id}")
    void update(News news);

    @Delete("DELETE FROM news WHERE id = #{id}")
    void deleteById(@Param("id") Integer id);
}

mapper/GoodsMapper.java

package org.example.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.example.pojo.Goods;

import java.util.List;

/**
 * 商品Mapper - sql都写在mybatis xml文件中
 */
@Mapper
public interface GoodsMapper {
    List<Goods> findAll();

    Goods findById(Integer id);

    void insert(Goods goods);

    void update(Goods goods);

    void deleteById(Integer id);
}

service/NewsService.java

package org.example.service;


import org.example.mapper.NewsMapper;
import org.example.pojo.News;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsService {
    @Autowired
    private NewsMapper newsMapper;

    public List<News> getAllNews() {
        return newsMapper.findAll();
    }

    public News getNewsById(Integer id) {
        return newsMapper.findById(id);
    }

    public void saveNews(News news) {
        newsMapper.insert(news);
    }

    public void updateNews(News news) {
        newsMapper.update(news);
    }

    public void deleteNews(Integer id) {
        newsMapper.deleteById(id);
    }
}

service/GoodsService.java

package org.example.service;

import com.github.pagehelper.PageHelper;
import org.example.mapper.GoodsMapper;
import org.example.pojo.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    public List<Goods> getAllGoods(int pageNum, int pageSize) {
        // 使用PageHelper设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        return goodsMapper.findAll();
    }

    public Goods getGoodsById(Integer id) {
        return goodsMapper.findById(id);
    }

    public void saveGoods(Goods goods) {
        goodsMapper.insert(goods);
    }

    public void updateGoods(Goods goods) {
        goodsMapper.update(goods);
    }

    public void deleteGoods(Integer id) {
        goodsMapper.deleteById(id);
    }
}

resources/mapper/GoodsMapper.xml

<?xml 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="org.example.mapper.GoodsMapper">

    <!-- 查询所有商品 -->
    <select id="findAll" resultType="org.example.pojo.Goods">
        SELECT * FROM goods order by id desc
    </select>

    <!-- 根据ID查询商品 -->
    <select id="findById" parameterType="int" resultType="org.example.pojo.Goods">
        SELECT * FROM goods WHERE id = #{id}
    </select>

    <!-- 插入商品 -->
    <insert id="insert" parameterType="org.example.pojo.Goods">
        INSERT INTO goods (name, description) VALUES (#{name}, #{description})
    </insert>

    <!-- 更新商品 -->
    <update id="update" parameterType="org.example.pojo.Goods">
        UPDATE goods SET name = #{name}, description = #{description} WHERE id = #{id}
    </update>

    <!-- 删除商品 -->
    <delete id="deleteById" parameterType="int">
        DELETE FROM goods WHERE id = #{id}
    </delete>

</mapper>

4、模版文件

1)news模块

news/list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>News List</title>
</head>
<body>
<h1>News List</h1>
<a href="/news/add">Add News</a>
<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Content</th>
        <th>Actions</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="news : ${newsList}">
        <td th:text="${news.id}"></td>
        <td th:text="${news.title}"></td>
        <td th:text="${news.content}"></td>
        <td>
            <a th:href="@{'/news/edit/' + ${news.id}}">Edit</a>
            <a th:href="@{'/news/delete/' + ${news.id}}">Delete</a>
        </td>
    </tr>
    </tbody>
</table>
</body>
</html>

news/add.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Add News</title>
</head>
<body>
<h1>Add News</h1>
<form th:action="@{/news/save}" method="post" th:object="${news}">
    <label>Title:</label>
    <input type="text" th:field="*{title}" />
    <br />
    <label>Content:</label>
    <textarea th:field="*{content}"></textarea>
    <br />
    <button type="submit">Save</button>
</form>
</body>
</html>

news/edit.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Edit News</title>
</head>
<body>
<h1>Edit News</h1>
<form th:action="@{/news/update}" method="post" th:object="${news}">
  <input type="hidden" th:field="*{id}" />
  <label>Title:</label>
  <input type="text" th:field="*{title}" />
  <br />
  <label>Content:</label>
  <textarea th:field="*{content}"></textarea>
  <br />
  <button type="submit">Update</button>
</form>
</body>
</html>

2)goods模块

goods/list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Goods List</title>
</head>
<body>
<h1>Goods List</h1>
<a href="/goods/add">Add Goods</a>
<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Description</th>
        <th>Actions</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="goods : ${goodsList}">
        <td th:text="${goods.id}"></td>
        <td th:text="${goods.name}"></td>
        <td th:text="${goods.description}"></td>
        <td>
            <a th:href="@{'/goods/edit/' + ${goods.id}}">Edit</a>
            <a th:href="@{'/goods/delete/' + ${goods.id}}">Delete</a>
        </td>
    </tr>
    </tbody>
</table>

<!-- 分页导航条 -->
<div>
    <!-- 首页 -->
    <a th:href="@{/goods/(pageNum=1)}" th:text="'首页'" />

    <!-- 上一页 -->
    <a th:href="@{/goods/(pageNum=${pageNum > 1 ? pageNum - 1 : 1})}" th:text="'上一页'" th:if="${pageNum > 1}"/>
    <span th:if="${pageNum == 1}" th:text="'上一页'" style="color: #ccc; cursor: default;" />

    <!-- 当前页 -->
    <span th:text="'第 ' + ${pageNum} + ' 页'" />

    <!-- 下一页 -->
    <a th:href="@{/goods/(pageNum=${pageNum + 1})}" th:text="'下一页'" th:if="${pageNum < totalPages}" />
    <span th:if="${pageNum >= totalPages}" th:text="'下一页'" style="color: #ccc; cursor: default;" />

    <!-- 尾页 -->
    <a th:href="@{/goods/(pageNum=${totalPages})}" th:text="'尾页'" th:if="${pageNum < totalPages}" />
    <span th:if="${pageNum >= totalPages}" th:text="'尾页'" style="color: #ccc; cursor: default;" />
</div>

</body>
</html>

goods/add.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Add Goods</title>
</head>
<body>
<h1>Add Goods</h1>
<form th:action="@{/goods/save}" method="post" th:object="${goods}">
  <label>Name:</label>
  <input type="text" th:field="*{name}" />
  <br />
  <label>Description:</label>
  <textarea th:field="*{description}"></textarea>
  <br />
  <button type="submit">Save</button>
</form>
</body>
</html>

goods/edit.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Edit Goods</title>
</head>
<body>
<h1>Edit Goods</h1>
<form th:action="@{/goods/update}" method="post" th:object="${goods}">
  <input type="hidden" th:field="*{id}" />
  <label>Name:</label>
  <input type="text" th:field="*{name}" />
  <br />
  <label>Description:</label>
  <textarea th:field="*{description}"></textarea>
  <br />
  <button type="submit">Update</button>
</form>
</body>
</html>

四、测试结果

1、news

列表

添加

更新

2、goods

列表

添加

更新

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐