Spring boot jpa(二)repository

前言

本文介绍如何使用spring boot jpa repository如何使用该,本文承接上一篇文章。本文介绍如何使用程序操作数据库。

开发环境如下:

项目 说明
jdk 1.8
idea 2017-03(已经安装lombok插件)
mysql 5.6 推荐使用docker
navicat mysql 客户端

操作步骤

  • 新建repository类:AuthorRepository
package org.nick.bootstart.repositories;
import org.nick.bootstart.model.Author;
import org.springframework.data.repository.CrudRepository;

public interface AuthorRepository extends CrudRepository<Author,Long>{

}
  • 新建控制类AuthorController
package org.nick.bootstart.controller;
import org.nick.bootstart.model.Author;
import org.nick.bootstart.repositories.AuthorRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class AuthorController {

    AuthorRepository authorRepository;

    public AuthorController(AuthorRepository authorRepository) {
        this.authorRepository = authorRepository;
    }

    @RequestMapping("/authors")
    public String getAuthors(Model model){
        Iterable<Author> authors = authorRepository.findAll();
        model.addAttribute("authors",authorRepository.findAll());
        return  "authors";
    }

}
  • 新建模版文件:./src/main/resources/templates/authors.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleft.org">
<head>
    <meta charset="UTF-8" >
    <title>Title</title>
</head>
<body>
<h1>author list</h1>
<table>
    <tr>
        <th>id</th>
        <th>frist name</th>
        <th>last name</th>
    </tr>
    <tr th:each="author : ${authors}">
        <td th:text="${author.id}"></td>
        <td th:text="${author.firstName}"></td>
        <td th:text="${author.lastName}"></td>
    </tr>
</table>
</body>
</html>
  • 执行查看效果 .
    image.png

总结

  • 从数据库中读写对象只需要实现CrudRepository类即可;
  • 控制类可标注@Controller,对应控制方法标注@RequestMapping,控制方法需要返回值为模版文件名字;
  • 使用模版文件,需要在pom中添加
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容