1. 程式人生 > 其它 >Springboot 2.3.5使用 Mybatis 實現增刪改查(單表),並實現增改獲取對應的id

Springboot 2.3.5使用 Mybatis 實現增刪改查(單表),並實現增改獲取對應的id

參考

  1. springboot+mybatis 插入新資料並返回該資料id值
  2. Mybatis XML 對映器
  3. mybatis中的sql語句的返回值

知識點

  1. 取出剛剛插入的id

    1. 通過給insert、update的xml對映語句設定useGeneratedKeys與keyProperty屬性,可以讓mybatis取出由資料庫內部生成的主鍵,如果生成列不止一個,可以用逗號分隔多個屬性名稱。
    2. 需要將文章實體例項化之後作為引數傳入Mapper的查詢方法,這樣mybatis就會按照 1 的設定將新增/修改的id傳入到文章實體內,然後把文章實體返回給控制器,控制器就能夠獲取到剛剛插入/修改的id了。
  2. 增刪改查語句使用不同的標籤進行處理,查詢:select、新增:insert、修改:update、刪除:delete。

  3. 語句預設返回值 ,引用自mybatis中的sql語句的返回值

    1. select語句

      1. 正確執行時,返回查詢的結果或結果集
      2. 未查詢到結果,返回值為null
    2. insert語句

      1. 正確執行時,返回在資料庫中影響的行數
      2. 插入資料失敗,丟擲com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
    3. update語句

      1. 正確執行時,返回在資料庫中匹配的行數
      2. 插入資料失敗,丟擲com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
    4. delete語句

      1. 正確執行時,返回在資料庫中影響的行數
      2. 插入資料失敗,丟擲com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException

(單表)實現增刪改查程式碼

  1. 實體

    1. 文章實體 entity/ArticleEntity.java
    		/**
    		 * 文章實體
    		 * @Author 夏秋初
    		 * @Date 2021/8/13 10:10
    		 */
    		@Data
    		@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
    		public class ArticleEntity implements Serializable {
    			/**
    			 * 序列化安全
    			 */
    			private static final long serialVersionUID = 1L;
    			private Integer id;
    			private String title;
    			private String introduction;
    			private Date createdAt;
    			private Date updatedAt;
    			private String content;
    			private Integer shows;
    			private Integer likes;
    		}
    
    1. 文章新增Dto dto/admin/request/ArticleAddDto.java
    	/**
    	 * @Author 夏秋初
    	 * @Date 2021/8/16 10:45
    	 */
    	@Data
    	public class ArticleAddDto {
    		private String title;
    		private String introduction;
    		private String content;
    	}
    
    1. 文章更新Dto dto/admin/request/ArticleUpdateDto.java
    	/**
    	 * @Author 夏秋初
    	 * @Date 2021/8/16 10:45
    	 */
    	@Data
    	public class ArticleUpdateDto {
    		private String title;
    		private String introduction;
    		private String content;
    	}
    
  2. 文章xml對映檔案 resources/mappers/ArticleMapper.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">
<!--這裡對應Maper介面類的名稱空間-->
<mapper namespace="com.xxx.blog.mapper.ArticleMapper">
    <!--    這裡 resultType 對應響應實體類,也可以是其他型別,請參考文件-->
    <select id="findById" parameterType="int" resultType="com.xxx.blog.entity.ArticleEntity">
        select * from `articles` where id = #{id}
    </select>
    <select id="findByPaging" resultType="com.xxx.blog.entity.ArticleEntity" parameterType="map">
        select
        *
        from `articles`
    </select>
    <insert id="add" useGeneratedKeys="true"
            keyProperty="id" parameterType="com.xxx.blog.entity.ArticleEntity">
        insert into articles (title, introduction,content,created_at,updated_at) values(#{title}, #{introduction},#{content},#{createdAt},#{updatedAt})
    </insert>
    <update id="update" useGeneratedKeys="true" keyProperty="id" parameterType="com.xxx.blog.entity.ArticleEntity">
        update articles set
                title = #{title}, introduction = #{introduction}, content=#{content}, updated_at = #{updatedAt}
        where id = #{id}
    </update>
    <delete id="delete" parameterType="int">
        delete from articles where id = #{id}
    </delete>
</mapper>
  1. 文章Mapper類 mapper/ArticleMapper.java
/**
 * @Author 夏秋初
 * @Date 2021/8/13 10:24
 */
@Mapper
public interface ArticleMapper {
    public ArticleEntity findById(Integer id);
    public List<ArticleEntity> findByPaging(Map param);
    public Integer add(ArticleEntity articleEntity);
    public Integer update(ArticleEntity articleEntity);
    public Integer delete(Integer id);
}
  1. 文章 service service/ArticleService.java
/**
 * @Author 夏秋初
 * @Date 2021/8/13 10:24
 */
@Service
public class ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    public ArticleEntity findById(Integer id){
        return articleMapper.findById(id);
    }

    /**
     * 分頁查詢
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    public PageInfo findByPaging(Integer pageNum, Integer pageSize,Map map){
        PageHelper.startPage(pageNum, pageSize);
        List<ArticleEntity> articleEntityPage = articleMapper.findByPaging(map);
        PageInfo pageInfo = new PageInfo(articleEntityPage);
        return pageInfo;
    }

    /**
     * 建立一個文章
     * @param articleAddDto
     * @return
     */
    public ArticleEntity add(ArticleAddDto articleAddDto){
        ArticleEntity articleEntity = new ArticleEntity();
        articleEntity.setTitle(articleAddDto.getTitle());
        articleEntity.setIntroduction(articleAddDto.getIntroduction());
        articleEntity.setContent(articleAddDto.getContent());
        Date date = new Date();
        articleEntity.setCreatedAt(date);
        articleEntity.setUpdatedAt(date);
        articleMapper.add(articleEntity);
        return articleEntity;
    }

    /**
     *  更新一個文章
     * @param articleUpdateDto
     * @return
     */
    public ArticleEntity update( Integer id,ArticleUpdateDto articleUpdateDto){
        ArticleEntity articleEntity = new ArticleEntity();
        articleEntity.setId(id);
        articleEntity.setTitle(articleUpdateDto.getTitle());
        articleEntity.setIntroduction(articleUpdateDto.getIntroduction());
        articleEntity.setContent(articleUpdateDto.getContent());
        articleEntity.setUpdatedAt(new Date());
        articleMapper.update(articleEntity);
        return articleEntity;
    }
    public Integer delete( Integer id){
        return articleMapper.delete(id);
    }
}
  1. 文章控制器
/**
 * @Author 夏秋初
 * @Date 2021/8/13 10:26
 */
@RestController
@RequestMapping("admin/v1/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;

    /**
     * 獲取文章分頁
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "", produces = "application/json;charset=UTF-8")
    public ResponseEntity<CustomResponseStructureDto<PageInfo>> list(@RequestParam(name = "page_num", defaultValue = "1") Integer pageNum, @RequestParam(name = "page_size",defaultValue = "10") Integer pageSize){
        Map<String, String> map = new HashMap<>();
        PageInfo pageInfo = articleService.findByPaging(pageNum, pageSize, map);
        return ResponseEntity.ok(new CustomResponseStructureDto(0, pageInfo, "成功"));
    }

    /**
     * 獲取指定id
     * @param id
     * @return
     */
    @GetMapping(value = "{id}", produces = "application/json;charset=UTF-8")
    public ResponseEntity<CustomResponseStructureDto<ArticleEntity>> list(@PathVariable("id") Integer id){
        ArticleEntity article = articleService.findById(id);
        return ResponseEntity.ok(new CustomResponseStructureDto<ArticleEntity>(0, article, "成功"));
    }

    /**
     * 新增文章
     * @param articleAddDto
     * @return
     */
    @PostMapping(value = "", produces = "application/json;charset=UTF-8")
    public ResponseEntity<CustomResponseStructureDto<ArticleEntity>> add(@RequestBody ArticleAddDto articleAddDto){
        return ResponseEntity.ok(new CustomResponseStructureDto<ArticleEntity>(0, articleService.add(articleAddDto), ""));
    }

    /**
     * 更新文章
     * @param id
     * @param articleUpdateDto
     * @return
     */
    @PutMapping(value = "{id}", produces = "application/json;charset=UTF-8")
    public ResponseEntity<CustomResponseStructureDto<ArticleEntity>> add(@PathVariable("id") Integer id, @RequestBody ArticleUpdateDto articleUpdateDto){
        return ResponseEntity.ok(new CustomResponseStructureDto<ArticleEntity>(0, articleService.update(id, articleUpdateDto), ""));
    }

    /**
     * 刪除文章
     * @param id
     * @return
     */
    @DeleteMapping(value = "{id}", produces = "application/json;charset=UTF-8")
    public ResponseEntity<CustomResponseStructureDto<Object>> delete(@PathVariable("id") Integer id){
        articleService.delete(id);
        return ResponseEntity.ok(new CustomResponseStructureDto<Object>(0, null , ""));
    }
}
如果覺得文章對您有幫助,希望您能 關注+推薦 哦