實(shí)現(xiàn)文章添加和查詢接口

文件變更

本節(jié)文件變更如下

創(chuàng)建 post(文章)表

DROP TABLE IF EXISTS `post`;
CREATE TABLE `post` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `author_id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

Post 類

新增 Post.java

public class Post {
    private Integer id;
    private User author;
    private Integer authorId;    // 作者的 id
    private String title;       // 文章標(biāo)題
    private String content;     // 文章內(nèi)容
    private Date createTime;
    
  // ... getter and setter
}

Controller 層

新增 PostApi.java

/**
 * 文章接口
 */
@RestController
@RequestMapping("/api/post")
public class PostApi {
    private PostService postService;

    @Autowired
    public PostApi(PostService postService) {
        this.postService = postService;
    }

    @PostMapping("")
    @LoginRequired
    public Post add(@RequestBody Post post, @CurrentUser User user) {
        post.setAuthorId(user.getId());
        post = postService.add(post);
        return post;
    }

    @GetMapping("/{id}")
    public Object findById(@PathVariable int id) {
        Post post = postService.findById(id);
        if (post == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", "文章不存在");
            return jsonObject;
        } else {
            return post;
        }
    }
}

add 方法用上了前兩節(jié)寫的 @LoginRequired 注解進(jìn)行登錄攔截@CurrentUser 注解獲取當(dāng)前登錄用戶。

Service 層

新增 PostService.java

@Service
public class PostService {
    private PostMapper postMapper;

    @Autowired
    public PostService(PostMapper postMapper) {
        this.postMapper = postMapper;
    }

    @Transactional
    public Post add(Post post) {
        postMapper.add(post);
        return findById(post.getId());
    }

    public Post findById(Integer id) {
        Post param = new Post();
        param.setId(id);
        return postMapper.findOne(param);
    }
}

這里說下 @Transactional (事務(wù)管理)注解,假如這個(gè)這個(gè)方法里面有多個(gè)數(shù)據(jù)庫操作,想要某個(gè)操作出錯(cuò)時(shí)回滾這個(gè)方法里面的所有操作,就在這個(gè)方法里面加上這個(gè)注解。比如 add 方法,假設(shè)第一步添加成功,第二步查詢失敗,因?yàn)橛?@Transactional 注解的存在,拋出異常之后數(shù)據(jù)庫也會(huì)回滾到未添加時(shí)的狀態(tài)。

Mapper 接口

新增 PostMapper.java

public interface PostMapper {
    int add(Post post);

    Post findOne(Post param);
}

新增 PostMapper.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="com.hpm.blog.mapper.PostMapper">
    <resultMap id="PostResultMap" type="com.hpm.blog.model.Post" autoMapping="true">
        <id column="id" property="id" />    <!-- id 很重要 -->
        <!--關(guān)聯(lián)作者,post 表和 user 表可能會(huì)用一些字段重復(fù),比如 id 這個(gè)屬性,所以給 user 表的字段加上columnPrefix(前綴)-->
        <association property="author" autoMapping="true" columnPrefix="author__"
                     javaType="com.hpm.blog.model.User">
            <id column="author_id" property="id" />
        </association>
    </resultMap>

    <insert id="add" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO post (author_id, title, content) VALUES (#{authorId}, #{title}, #{content});
    </insert>

    <select id="findOne" resultMap="PostResultMap">
      SELECT
        post.id,
        post.author_id ,
        post.title ,
        post.content ,
        post.create_time ,
        post.update_time,
        <!-- 作者信息,password 不需要就不查了 -->
        `user`.id as author__id,
        `user`.`name` as author__name
      FROM post
      LEFT JOIN `user` ON `user`.id=post.author_id
      <where>
          <if test="id!=null">
             AND post.id=#{id}
          </if>
      </where>
    </select>
</mapper>

查詢接口用了關(guān)聯(lián)查詢,并且寫了個(gè) ResultMap 來映射文章和用戶的一對(duì)一關(guān)系。associationcolumnPrefix 屬性在多表查詢中特別有用。

測試

重啟項(xiàng)目,使用 postman 發(fā)送一個(gè) post 請求到 /api/post


不要忘了帶上 token

查看項(xiàng)目完整代碼

項(xiàng)目地址: https://github.com/hyrijk/spring-boot-blog
克隆項(xiàng)目到本地

git clone https://github.com/hyrijk/spring-boot-blog.git

checkout 到當(dāng)前版本

git checkout 239b170322e5734a06dde32c1648a3cde53acf8a

完。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,366評(píng)論 25 708
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,290評(píng)論 6 342
  • 今天用了半個(gè)多小時(shí),畫了一只熊貓。 暈染的技巧還是差很多~ 上圖: 下面是步驟圖 今天畫得比較簡單,所以直接起稿。...
    機(jī)器貓的魚豆腐閱讀 710評(píng)論 2 5
  • 認(rèn)識(shí)簡書,可以說真是一個(gè)巧合,那是在網(wǎng)易云客堂學(xué)習(xí)H5的時(shí)候,無意間看到這么一個(gè)東西,出于好奇心,才來到了這個(gè)地方...
    老衲瘋了閱讀 1,130評(píng)論 0 51
  • 少女時(shí)期,我的心時(shí)常被一些美麗的心事所填滿。這些美麗的心事就像蜜一樣的甜在心里,讓我對(duì)未知的生活充滿了期待和憧憬。...
    山間的楓林閱讀 473評(píng)論 0 0

友情鏈接更多精彩內(nèi)容