11
7

More than 3 years have passed since last update.

Spring Boot でテーブルのデータをビューに出力するまでの流れ

Last updated at Posted at 2019-11-01

事前に必要なこと

・DBへの接続設定を行う

大まかな流れ

Usersテーブルからデータを取得し、表示するという設定です。

  1. エンティティを作成する
  2. リポジトリを作成する
  3. コントローラを作成する
  4. ビューを作成する

エンティティを作成する

Usersテーブルのデータを取得した値を保存するのに利用する。

com.example.entities.UsersEntity.java

@Entity
@Table(name="Users")
public class UsersEntity{
  @Id
  private Integer id;
  private String name;

  public Integer getId(){
    return id;
  }

  public String getName(){
    return name;
  }
}

リポジトリを作成する

リポジトリはDBとデータのやり取りを行う。

com.example.repositories.UsersRepository.java
import com.example.entities.UsersEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UsersRepository extends JpaRepository<UsersEntity, Integer>{
}

コントローラを作成する

com.example.controller.UserController.java
@Controller
public class UserController{
  @Autowired
  // 変数に代入
  private UsersRepository usersRepository;

  // このURLにアクセスした際の動作
  @RequestMapping("/index") 
  public String index(Model model){
    List<UsersEntity> users = usersRepository.findAll();
    model.addAttribute("userlist", users);
    return "view/user/index";
  }
}

ビューを作成する

/view/user/index.html
  <table>
    <tr th:each="users : ${userlist}">
      <td th:text="${users.id}"></td>
      <td th:text="${users.name}"></td>
    </tr>
  </table>
11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7