ssm增删改查 (spring、springmvc、mybatis与mybatisplus)整合

个人学习笔记,还用到了vue、axios、ajax等前端技术,赶紧补习…!!

文章目录

  • 环境配置
  • 一、pom.xml
  • 二、配置文件
  • 三、dao接口层与测试
  • 四、service接口层与实现类的测试
  • 五、controller
  • 六、页面编写


环境配置

  • JDK 1.8
  • IDEA 2021.2.3
  • maven 3.8.4

代码放在这里了:https://github.com/chen22-x/springboot_crud

模块路径如下:
ssm增删改查 (spring、springmvc、mybatis与mybatisplus)整合_第1张图片
主页面效果图:(实现查询、新增、删除、修改以及分页与页面跳转功能)
ssm增删改查 (spring、springmvc、mybatis与mybatisplus)整合_第2张图片


一、pom.xml

基于springboot创建项目,导入第三方相关依赖:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com</groupId>
    <artifactId>springboot_crud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_crud</name>
    <description>springboot_crud</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

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

        <!--mysql数据库驱动        -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

        <!--druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <!--mybatis-plus第三方库-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

二、配置文件

在类路径下(resources)创建后缀名为yml的配置文件,并配置数据库连接信息、mybatis-plus全局配置信息等;

#端口设置
server:
  port: 80

#连接数据库
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql:///ssm?serverTimezone=UTC
      username: root
      password: root

# mybatis-plus全局配置
mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_  #忽略数据表的前缀
      id-type: auto  #id设置为数据表的自增,不采用雪花算法
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #日志输出

三、dao接口层与测试

dao接口层继承了BaseMapper接口
BookDao接口:

@Mapper
public interface BookDao extends BaseMapper<Book> {
}

测试省略

四、service接口层与实现类的测试

service接口继承了IService接口
IBookService接口:


/**
 * 继承通用接口IService
 */
public interface IBookService extends IService<Book> {
    /**
     * 以下为自定义crud功能
     * @param book
     * @return
     */
    boolean saveBook(Book book);
    boolean modify(Book book);
    boolean delete(Integer id);
    IPage<Book> getPage(int currentPage, int pageSize);

    IPage<Book> getPage(int currentPage, int pageSize, Book book);
}

BookServiceImpl实现类:

@Service
//IService通用接口 ServiceImpl通用实现类
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements IBookService {

    //注入BookDao
    @Autowired
    private BookDao bookDao;

    /**
     * 保存信息
     * @param book
     * @return
     */
    @Override
    public boolean saveBook(Book book) {
        return bookDao.insert(book) > 0;
    }

    /**
     * 修改信息
     * @param book
     * @return
     */
    @Override
    public boolean modify(Book book) {
        return bookDao.updateById(book) > 0;
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @Override
    public boolean delete(Integer id) {
        return bookDao.deleteById(id) > 0;
    }


    /**
     * 分页
     *
     * @param currentPage 当前页
     * @param pageSize    每页显示条数
     * @return
     */
    @Override
    public IPage<Book> getPage(int currentPage, int pageSize) {
        IPage<Book> page = new Page<>(currentPage, pageSize);
        bookDao.selectPage(page, null);
        return page;
    }

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param book 根据拼接搜索请求参数来执行sql查询
     * @return
     */
    @Override
    public IPage<Book> getPage(int currentPage, int pageSize, Book book) {
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        //拼接搜索查询语句
        wrapper.like(Strings.isNotBlank(book.getType()), Book::getType, book.getType());
        wrapper.like(Strings.isNotBlank(book.getName()), Book::getName, book.getName());
        wrapper.like(Strings.isNotBlank(book.getDescription()), Book::getDescription, book.getDescription());
        IPage<Book> page = new Page<>(currentPage, pageSize);
        bookDao.selectPage(page, wrapper);
        return page;
    }
}

测试省略

五、controller


@RestController //相当于@Controller和@ResponseBody
@RequestMapping("/books")//请求映射,根据请求方法的类型(put/post/put/delete)来匹配对应的控制器方法
public class BookController {
    @Autowired
    private IBookService bookService;

    @GetMapping
    public R getAll() {
        return new R(true, bookService.list());
    }

    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        if (book.getName().equals("abc"))  //设置添加""异常
            throw new IOException();
        boolean flag = bookService.save(book);
        return new R(flag, flag ? "添加成功.." : "添加失败!!");
    }

    //@RequestBody:从请求体获取请求参数赋值给方法形参
    @PutMapping
    public R update(@RequestBody Book book) {
        return new R(bookService.modify(book));
    }

    //从请求映射地址获取id值(利用{}占位符)
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(bookService.delete(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, bookService.getById(id));
    }

//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable("currentPage") int currentPage,
//                     @PathVariable("pageSize") int pageSize) {
//        IPage page = bookService.getPage(currentPage, pageSize);
//        //若当前页码也没有数据,即当前页码大于总页码数,则将总页码数作为当前页码值
//        if (page.getPages()
//            page = bookService.getPage((int) page.getPages(), pageSize);
//        }
//        return new R(true, page);
//    }


//    SELECT id,type,name,description FROM tbl_book WHERE (name LIKE ? AND description LIKE ?) LIMIT ?
    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable("currentPage") int currentPage,
                     @PathVariable("pageSize") int pageSize,Book book) {
        IPage<Book> page = bookService.getPage(currentPage, pageSize,book);
        //若当前页码也没有数据,即当前页码大于总页码数,则将总页码数作为当前页码值
        if (page.getPages() < currentPage) {
            page = bookService.getPage((int) page.getPages(), pageSize,book);
        }
        return new R(true, page);
    }
}

六、页面编写

放在resources/static/pages/books.html

你可能感兴趣的:(mybatis,spring,java,restful)