当前位置:   article > 正文

springboot+mybatis实现简单的增、删、查、改_springbootmybatis增删改查

springbootmybatis增删改查

这篇文章主要针对java初学者,详细介绍怎么创建一个基本的springboot项目来对数据库进行crud操作。

第一步:创建springboot项目

在IntelliJ IDEA中通过spring initilizer创建springboot项目如图,依次点击左上角的菜单栏中的File >> New >> Project...

然后在打开的窗口左侧选择Spring Initilizer,在右侧面板:

  • 修改项目名为springboot-crud
  • 修改包名为com.example.springboot
  • 修改java版本为8

然后点击Next按钮

接着点击Finish按钮,等待idea创建并下载springboot项目。

第二步:修改pom.xml

修改pom.xml配置文件,修改springboot的版本为2.5.9,并添加和必要的依赖,删除test依赖。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.9</version>
  9. <relativePath />
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>springboot-crud</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot-crud</name>
  15. <description>springboot+mybatis实现增删查改的入门项目</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <mysql.version>8.0.28</mysql.version>
  19. <druid.version>1.1.21</druid.version>
  20. <lombok.version>1.18.22</lombok.version>
  21. <mybatis.version>2.2.2</mybatis.version>
  22. </properties>
  23. <dependencies>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <!--lombok:自动生成getter、setter工具-->
  29. <dependency>
  30. <groupId>org.projectlombok</groupId>
  31. <artifactId>lombok</artifactId>
  32. <version>${lombok.version}</version>
  33. </dependency>
  34. <!--mysql驱动-->
  35. <dependency>
  36. <groupId>mysql</groupId>
  37. <artifactId>mysql-connector-java</artifactId>
  38. <version>${mysql.version}</version>
  39. </dependency>
  40. <!--druid数据库连接池-->
  41. <dependency>
  42. <groupId>com.alibaba</groupId>
  43. <artifactId>druid</artifactId>
  44. <version>${druid.version}</version>
  45. </dependency>
  46. <!--spring boot整合mybatis的依赖-->
  47. <dependency>
  48. <groupId>org.mybatis.spring.boot</groupId>
  49. <artifactId>mybatis-spring-boot-starter</artifactId>
  50. <version>${mybatis.version}</version>
  51. </dependency>
  52. </dependencies>
  53. <build>
  54. <plugins>
  55. <plugin>
  56. <groupId>org.springframework.boot</groupId>
  57. <artifactId>spring-boot-maven-plugin</artifactId>
  58. </plugin>
  59. </plugins>
  60. </build>
  61. </project>

第三步:准备数据库

创建一个数据库springboot-crud,然后执行项目doc/sql目录下的springboot-crud.sql

第四步:修改配置文件

springboot的配置文件有两种格式,即application.properties或application.yml。

推荐使用yml文件格式,重命名application.properties为application.yml。然后添加数据库的数据源设置,并修改项目的启动端口号为8083,然后设置mybatis的mapper.xml文件的位置以及日志隔离级别为debug(默认info)。

  1. spring:
  2. datasource:
  3. username: root
  4. password: root
  5. url: jdbc:mysql://localhost:3306/springboot-crud
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. type: com.alibaba.druid.pool.DruidDataSource
  8. server:
  9. port: 8083
  10. mybatis:
  11. mapper-locations: classpath:mapper/*Mapper.xml
  12. logging:
  13. level:
  14. springfox: error
  15. com.example.springboot: debug

第五步:创建数据库对应的实体类

在项目的根目录com.example.springboot下创建entity包,然后在entity包下面创建一个实体类Song.java,并实现序列化接口Serializable。

  1. package com.example.springboot.entity;
  2. import com.fasterxml.jackson.annotation.JsonFormat;
  3. import lombok.Data;
  4. import java.io.Serializable;
  5. import java.time.LocalDateTime;
  6. /**
  7. * 歌曲
  8. * @author heyunlin
  9. * @version 1.0
  10. */
  11. @Data
  12. public class Song implements Serializable {
  13. private static final long serialVersionUID = 18L;
  14. private String id;
  15. /**
  16. * 歌曲名
  17. */
  18. private String name;
  19. /**
  20. * 歌手
  21. */
  22. private String singer;
  23. /**
  24. * 描述信息
  25. */
  26. private String note;
  27. /**
  28. * 最后一次修改时间
  29. */
  30. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
  31. private LocalDateTime lastUpdateTime;
  32. }

第六步:创建持久层接口

同样的,在项目根路径下创建mapper包,在mapper包下创建一个接口SongMapper,在接口上添加Spring组件注解@Repository。

  1. package com.example.springboot.mapper;
  2. import org.springframework.stereotype.Repository;
  3. /**
  4. * @author heyunlin
  5. * @version 1.0
  6. */
  7. @Repository
  8. public interface SongMapper {
  9. }

第七步:创建Mapper.xml文件

在src\main\resources下创建mapper包,然后在mapper包下面创建一个xml文件SongMapper.xml。其中namespace属性的值为SongMapper接口的全限定名

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.springboot.mapper.SongMapper">
  4. </mapper>

第八步:开启mapper包扫描

因为我们的持久层接口没有使用@Mapper注解,需要通过@MapperScan来配置mapper的包路径,通常我们会在一个单独的配置类上添加@MapperScan注解。

在项目根路径下创建config包,在config包下创建MybatisConfig.java,MybatisConfig上使用@Configuration将该类声明为配置类,通过@MapperScan注解指定mapper包扫描路径。

  1. package com.example.springboot.config;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.context.annotation.Configuration;
  4. /**
  5. * Mybatis配置文件
  6. * @author heyunlin
  7. * @version 1.0
  8. */
  9. @Configuration
  10. @MapperScan(basePackages = "com.example.springboot.mapper")
  11. public class MybatisConfig {
  12. }

第九步:创建业务层接口

在项目根路径下创建service包,在service包下创建接口SongService.java

  1. package com.example.springboot.service;
  2. /**
  3. * @author heyunlin
  4. * @version 1.0
  5. */
  6. public interface SongService {
  7. }

然后在service包下创建impl子包,创建一个SongService接口的实现类,并在实现类上使用@Service注解。

  1. package com.example.springboot.service.impl;
  2. import com.example.springboot.service.SongService;
  3. import org.springframework.stereotype.Service;
  4. /**
  5. * @author heyunlin
  6. * @version 1.0
  7. */
  8. @Service
  9. public class SongServiceImpl implements SongService {
  10. }

第十步:创建控制器类 

在项目根路径下创建controller包,在controller包下创建SongController.java类。

其中,@RestController注解是一个复合注解,由两个注解@RespondBody和@Controller组成,@RespondBody表示类下面的方法的返回值会被转换为json格式的字符串返回给调用者。

  1. package com.example.springboot.controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. /**
  5. * @author heyunlin
  6. * @version 1.0
  7. */
  8. @RestController
  9. @RequestMapping(path = "/song", produces="application/json;charset=utf-8")
  10. public class SongController {
  11. }

至此,项目所需的所有类都创建好了,项目完整目录结构如下图:

第十一步:开始开发业务功能

完成以上步骤之后,springboot项目的基本开发环境就搭建好了,接下来开始实现对歌曲表song的增删查改功能。

在此之前,需要把service层的SongService注入到SongController中,在这里使用《阿里巴巴开发规范》推荐的构造器注入方式。

  1. package com.example.springboot.controller;
  2. import com.example.springboot.service.SongService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. /**
  7. * @author heyunlin
  8. * @version 1.0
  9. */
  10. @RestController
  11. @RequestMapping(path = "/song", produces="application/json;charset=utf-8")
  12. public class SongController {
  13. private final SongService songService;
  14. @Autowired
  15. public SongController(SongService songService) {
  16. this.songService = songService;
  17. }
  18. }

1、添加歌曲

controller层

首先,在controller层创建一个方法,取名为insert,在方法内调用service层的对应方法,为了方便同样取名为insert

  1. package com.example.springboot.controller;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.service.SongService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * @author heyunlin
  10. * @version 1.0
  11. */
  12. @RestController
  13. @RequestMapping(path = "/song", produces="application/json;charset=utf-8")
  14. public class SongController {
  15. private final SongService songService;
  16. @Autowired
  17. public SongController(SongService songService) {
  18. this.songService = songService;
  19. }
  20. @RequestMapping(value = "/insert", method = RequestMethod.POST)
  21. public void insert(Song song) {
  22. songService.insert(song);
  23. }
  24. }

service层(业务层)

这时候,songService.insert(song);这行代码会报错,因为我们SongService接口没有这个方法,把鼠标移到红色的地方,键盘按alt+enter(回车键),选择第一个选项,在SongService创建insert()方法。

  1. package com.example.springboot.service;
  2. import com.example.springboot.entity.Song;
  3. /**
  4. * @author heyunlin
  5. * @version 1.0
  6. */
  7. public interface SongService {
  8. void insert(Song song);
  9. }

然后这时候发现SongService这个类也有红色的提示,因为SongServiceImpl实现了SongService接口,但是没有实现刚刚添加的insert()方法。

 如上图,点击红色的提示信息,会自动打开SongServiceImpl

我们把鼠标移到类上面,会提示实现方法,点击蓝色implement methods自动生成insert()方法。

  1. package com.example.springboot.service.impl;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.service.SongService;
  4. import org.springframework.stereotype.Service;
  5. /**
  6. * @author heyunlin
  7. * @version 1.0
  8. */
  9. @Service
  10. public class SongServiceImpl implements SongService {
  11. @Override
  12. public void insert(Song song) {
  13. }
  14. }

然后,为了能操作数据库,需要注入持久层的Mapper接口SongMapper,并调用持久层接口的方法来操作数据库。

因为表song的主键是非自增的,需要手动设置,使用当前时间生成uuid作为Id字段的值。

  1. package com.example.springboot.service.impl;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.mapper.SongMapper;
  4. import com.example.springboot.service.SongService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9. /**
  10. * @author heyunlin
  11. * @version 1.0
  12. */
  13. @Service
  14. public class SongServiceImpl implements SongService {
  15. private final SongMapper songMapper;
  16. @Autowired
  17. public SongServiceImpl(SongMapper songMapper) {
  18. this.songMapper = songMapper;
  19. }
  20. @Override
  21. public void insert(Song song) {
  22. song.setId(uuid());
  23. songMapper.insert(song);
  24. }
  25. /**
  26. * 根据当前时间生成UUID
  27. * @return String
  28. */
  29. private static String uuid() {
  30. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
  31. LocalDateTime localDate = LocalDateTime.now();
  32. return localDate.format(formatter);
  33. }
  34. }

mapper层(持久层)

同样的,在SongMapper接口上创建insert()方法,如果安装了mybatisx插件,也会有红色的提示,让你在SongMapper.xml上创建对应的方法。

  1. package com.example.springboot.mapper;
  2. import com.example.springboot.entity.Song;
  3. import org.springframework.stereotype.Repository;
  4. /**
  5. * @author heyunlin
  6. * @version 1.0
  7. */
  8. @Repository
  9. public interface SongMapper {
  10. void insert(Song song);
  11. }

 mapper.xml中添加一个insert标签,id属性值为方法名

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.springboot.mapper.SongMapper">
  4. <insert id="insert">
  5. insert into song(id, name, singer, note, last_update_time)
  6. values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})
  7. </insert>
  8. </mapper>

当然也可以在接口上使用注解来绑定SQL语句(推荐在xml文件中编写sql)

  1. package com.example.springboot.mapper;
  2. import com.example.springboot.entity.Song;
  3. import org.apache.ibatis.annotations.Insert;
  4. import org.springframework.stereotype.Repository;
  5. /**
  6. * @author heyunlin
  7. * @version 1.0
  8. */
  9. @Repository
  10. public interface SongMapper {
  11. @Insert("insert into song(id, name, singer, note, last_update_time) values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})")
  12. void insert(Song song);
  13. }

注意:只能通过注解或mapper.xml其中一个方法来绑定SQL语句,否则运行项目会报错。

2、删除歌曲

同样的,依次创建controller、service和mapper层的方法,然后在controller调用service,service调用mapper。

mapper层(持久层)

  1. package com.example.springboot.mapper;
  2. import com.example.springboot.entity.Song;
  3. import org.springframework.stereotype.Repository;
  4. /**
  5. * @author heyunlin
  6. * @version 1.0
  7. */
  8. @Repository
  9. public interface SongMapper {
  10. //@Insert("insert into song(id, name, singer, note, last_update_time) values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})")
  11. void insert(Song song);
  12. //@Delete("delete from song where id = #{id}")
  13. void deleteById(String id);
  14. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.springboot.mapper.SongMapper">
  4. <insert id="insert">
  5. insert into song(id, name, singer, note, last_update_time)
  6. values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})
  7. </insert>
  8. <delete id="deleteById">
  9. delete from song where id = #{id}
  10. </delete>
  11. </mapper>

service层(业务层)

SongService.java

  1. package com.example.springboot.service;
  2. import com.example.springboot.entity.Song;
  3. /**
  4. * @author heyunlin
  5. * @version 1.0
  6. */
  7. public interface SongService {
  8. void insert(Song song);
  9. void deleteById(String id);
  10. }

 SongServiceImpl

  1. package com.example.springboot.service.impl;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.mapper.SongMapper;
  4. import com.example.springboot.service.SongService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * @author heyunlin
  9. * @version 1.0
  10. */
  11. @Service
  12. public class SongServiceImpl implements SongService {
  13. private final SongMapper songMapper;
  14. @Autowired
  15. public SongServiceImpl(SongMapper songMapper) {
  16. this.songMapper = songMapper;
  17. }
  18. @Override
  19. public void insert(Song song) {
  20. song.setId(uuid());
  21. songMapper.insert(song);
  22. }
  23. @Override
  24. public void deleteById(String id) {
  25. songMapper.deleteById(id);
  26. }
  27. /**
  28. * 根据当前时间生成UUID
  29. * @return String
  30. */
  31. private static String uuid() {
  32. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
  33. LocalDateTime localDate = LocalDateTime.now();
  34. return localDate.format(formatter);
  35. }
  36. }

controller层

在这里使用rest风格的请求方式,通过@PathVariable注解绑定路径参数,也就是下面歌曲编号(id)对应的字符串值

请求url格式

http://localhost:8083/song/deleteById/歌曲编号

例如,这时候id获取到的值为10011

http://localhost:8083/song/deleteById/10011

  1. package com.example.springboot.controller;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.service.SongService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RestController;
  9. /**
  10. * @author heyunlin
  11. * @version 1.0
  12. */
  13. @RestController
  14. @RequestMapping(path = "/song", produces="application/json;charset=utf-8")
  15. public class SongController {
  16. private final SongService songService;
  17. @Autowired
  18. public SongController(SongService songService) {
  19. this.songService = songService;
  20. }
  21. @RequestMapping(value = "/insert", method = RequestMethod.POST)
  22. public void insert(Song song) {
  23. songService.insert(song);
  24. }
  25. @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.GET)
  26. public void deleteById(@PathVariable("id") String id) {
  27. songService.deleteById(id);
  28. }
  29. }

3、修改歌曲信息

mapper层(持久层)

SongMapper.java

  1. package com.example.springboot.mapper;
  2. import com.example.springboot.entity.Song;
  3. import org.springframework.stereotype.Repository;
  4. /**
  5. * @author heyunlin
  6. * @version 1.0
  7. */
  8. @Repository
  9. public interface SongMapper {
  10. //@Insert("insert into song(id, name, singer, note, last_update_time) values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})")
  11. void insert(Song song);
  12. //@Delete("delete from song where id = #{id}")
  13. void deleteById(String id);
  14. // @Update("update song set name = #{name}, singer = #{singer}, note = #{note}, last_update_time = #{lastUpdateTime} where id = #{id}")
  15. void updateById(Song song);
  16. }

 SongMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.springboot.mapper.SongMapper">
  4. <insert id="insert">
  5. insert into song(id, name, singer, note, last_update_time)
  6. values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})
  7. </insert>
  8. <delete id="deleteById">
  9. delete from song where id = #{id}
  10. </delete>
  11. <update id="updateById">
  12. update song
  13. set
  14. name = #{name},
  15. singer = #{singer},
  16. note = #{note},
  17. last_update_time = #{lastUpdateTime}
  18. where id = #{id}
  19. </update>
  20. </mapper>

service层(业务层)

SongService.java

  1. package com.example.springboot.service;
  2. import com.example.springboot.entity.Song;
  3. /**
  4. * @author heyunlin
  5. * @version 1.0
  6. */
  7. public interface SongService {
  8. void insert(Song song);
  9. void deleteById(String id);
  10. void updateById(Song song);
  11. }

SongServiceImpl.java

  1. package com.example.springboot.service.impl;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.mapper.SongMapper;
  4. import com.example.springboot.service.SongService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9. /**
  10. * @author heyunlin
  11. * @version 1.0
  12. */
  13. @Service
  14. public class SongServiceImpl implements SongService {
  15. private final SongMapper songMapper;
  16. @Autowired
  17. public SongServiceImpl(SongMapper songMapper) {
  18. this.songMapper = songMapper;
  19. }
  20. @Override
  21. public void insert(Song song) {
  22. song.setId(uuid());
  23. songMapper.insert(song);
  24. }
  25. @Override
  26. public void deleteById(String id) {
  27. songMapper.deleteById(id);
  28. }
  29. @Override
  30. public void updateById(Song song) {
  31. song.setLastUpdateTime(LocalDateTime.now());
  32. songMapper.updateById(song);
  33. }
  34. /**
  35. * 根据当前时间生成UUID
  36. * @return String
  37. */
  38. private static String uuid() {
  39. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
  40. LocalDateTime localDate = LocalDateTime.now();
  41. return localDate.format(formatter);
  42. }
  43. }

controller层

  1. package com.example.springboot.controller;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.service.SongService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RestController;
  9. /**
  10. * @author heyunlin
  11. * @version 1.0
  12. */
  13. @RestController
  14. @RequestMapping(path = "/song", produces="application/json;charset=utf-8")
  15. public class SongController {
  16. private final SongService songService;
  17. @Autowired
  18. public SongController(SongService songService) {
  19. this.songService = songService;
  20. }
  21. @RequestMapping(value = "/insert", method = RequestMethod.POST)
  22. public void insert(Song song) {
  23. songService.insert(song);
  24. }
  25. @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.GET)
  26. public void deleteById(@PathVariable("id") String id) {
  27. songService.deleteById(id);
  28. }
  29. @RequestMapping(value = "/updateById", method = RequestMethod.POST)
  30. public void updateById(Song song) {
  31. songService.updateById(song);
  32. }
  33. }

4、查询歌曲详情

controller层

  1. package com.example.springboot.controller;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.service.SongService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.bind.annotation.RestController;
  9. /**
  10. * @author heyunlin
  11. * @version 1.0
  12. */
  13. @RestController
  14. @RequestMapping(path = "/song", produces="application/json;charset=utf-8")
  15. public class SongController {
  16. private final SongService songService;
  17. @Autowired
  18. public SongController(SongService songService) {
  19. this.songService = songService;
  20. }
  21. @RequestMapping(value = "/insert", method = RequestMethod.POST)
  22. public void insert(Song song) {
  23. songService.insert(song);
  24. }
  25. @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
  26. public void delete(@PathVariable("id") String id) {
  27. songService.delete(id);
  28. }
  29. @RequestMapping(value = "/update", method = RequestMethod.POST)
  30. public void update(Song song) {
  31. songService.update(song);
  32. }
  33. @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
  34. public Song selectById(@PathVariable("id") String id) {
  35. return songService.selectById(id);
  36. }
  37. }

service层(业务层)

SongService.java

  1. package com.example.springboot.service;
  2. import com.example.springboot.entity.Song;
  3. /**
  4. * @author heyunlin
  5. * @version 1.0
  6. */
  7. public interface SongService {
  8. void insert(Song song);
  9. void deleteById(String id);
  10. void updateById(Song song);
  11. Song selectById(String id);
  12. }

SongServiceImpl.java

  1. package com.example.springboot.service.impl;
  2. import com.example.springboot.entity.Song;
  3. import com.example.springboot.mapper.SongMapper;
  4. import com.example.springboot.service.SongService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.time.LocalDateTime;
  8. import java.time.format.DateTimeFormatter;
  9. /**
  10. * @author heyunlin
  11. * @version 1.0
  12. */
  13. @Service
  14. public class SongServiceImpl implements SongService {
  15. private final SongMapper songMapper;
  16. @Autowired
  17. public SongServiceImpl(SongMapper songMapper) {
  18. this.songMapper = songMapper;
  19. }
  20. @Override
  21. public void insert(Song song) {
  22. song.setId(uuid());
  23. songMapper.insert(song);
  24. }
  25. @Override
  26. public void deleteById(String id) {
  27. songMapper.deleteById(id);
  28. }
  29. @Override
  30. public void updateById(Song song) {
  31. song.setLastUpdateTime(LocalDateTime.now());
  32. songMapper.updateById(song);
  33. }
  34. @Override
  35. public Song selectById(String id) {
  36. return songMapper.selectById(id);
  37. }
  38. /**
  39. * 根据当前时间生成UUID
  40. * @return String
  41. */
  42. private static String uuid() {
  43. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
  44. LocalDateTime localDate = LocalDateTime.now();
  45. return localDate.format(formatter);
  46. }
  47. }

mapper层(持久层)

SongMapper.java

  1. package com.example.springboot.mapper;
  2. import com.example.springboot.entity.Song;
  3. import org.springframework.stereotype.Repository;
  4. /**
  5. * @author heyunlin
  6. * @version 1.0
  7. */
  8. @Repository
  9. public interface SongMapper {
  10. //@Insert("insert into song(id, name, singer, note, last_update_time) values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})")
  11. void insert(Song song);
  12. //@Delete("delete from song where id = #{id}")
  13. void deleteById(String id);
  14. // @Update("update song set name = #{name}, singer = #{singer}, note = #{note}, last_update_time = #{lastUpdateTime} where id = #{id}")
  15. void updateById(Song song);
  16. // @Select("select * from song where id = #{id})
  17. Song selectById(String id);
  18. }

 SongMapper.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.springboot.mapper.SongMapper">
  4. <insert id="insert">
  5. insert into song(id, name, singer, note, last_update_time)
  6. values(#{id}, #{name}, #{singer}, #{note}, #{lastUpdateTime})
  7. </insert>
  8. <delete id="deleteById">
  9. delete from song where id = #{id}
  10. </delete>
  11. <update id="updateById">
  12. update song set name = #{name}, singer = #{singer}, note = #{note}, last_update_time = #{lastUpdateTime} where id = #{id}
  13. </update>
  14. <select id="selectById" resultType="com.example.springboot.entity.Song">
  15. select id, name, singer, note, last_update_time as lastUpdateTime from song where id = #{id}
  16. </select>
  17. </mapper>

最后,我们简单测试一下写的4个接口,推荐使用postman进行测试,可通过以下网盘链接下载

下载postmanicon-default.png?t=N7T8https://pan.baidu.com/s/1ViOqK6pp_Yj0Wfi2vAJsnA?pwd=yr5a好了,文章就分享到这里了,代码已开源,按需获取,如果这篇文章对你有所帮助,不要忘了点赞+收藏哦~

springboot+mybatis实现简单的增删查改案例项目icon-default.png?t=N7T8https://gitee.com/he-yunlin/springboot-crud.git

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

闽ICP备14008679号