[SpringBoot2.4.3] DAO

データベースアクセスする際のオブジェクト
Data Access Object

Dao interface

package com.example.demo;

import java.io.Serializable;
import java.util.List;

public interface MyDataDao <T> extends Serializable {
	public List<T> getAll();
}

MyDataDaoImpl.java

package com.example.demo;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

@Repository
public class MyDataDaoImpl implements MyDataDao<MyData> {
	private static final long serialVersionUID = 1L;
	
	private EntityManager entityManager;
	
	public MyDataDaoImpl() {
		super();
	}
	public MyDataDaoImpl(EntityManager manager) {
		this();
		entityManager = manager;
	}
	
	@Override
	public List<MyData> getAll(){
		Query query = entityManager.createQuery("from MyData");
		@SuppressWarnings("unchecked")
		List<MyData> list = query.getResultList();
		entityManager.close();
		return list;
	}

}

Controller

@Controller
public class HelloController {

	@Autowired
	MyDataRepository repository;
	
	@PersistenceContext
	EntityManager entityManager;
	
	MyDataDaoImpl dao;
	
	@PostConstruct
	public void init() {
		dao = new MyDataDaoImpl(entityManager);
		MyData d1 = new MyData();
		d1.setName("yamada");
		d1.setAge(20);
		d1.setMail("yamada@gmail.com");
		d1.setMemo("090999999");
		repository.saveAndFlush(d1);
		MyData d2 = new MyData();
		d2.setName("hanako");
		d2.setAge(18);
		d2.setMail("hanako@gmail.com");
		d2.setMemo("080888888");
		repository.saveAndFlush(d2);
		MyData d3 = new MyData();
		d3.setName("sachiko");
		d3.setAge(35);
		d3.setMail("sachiko@gmail.com");
		d3.setMemo("070777777");
		repository.saveAndFlush(d3);
	}	
	
	@RequestMapping(value="/", method=RequestMethod.GET)
	public ModelAndView index(
			@ModelAttribute("formModel") MyData mydata,
			ModelAndView mav) {
		mav.setViewName("index");
		mav.addObject("msg","this is sample content.");
		Iterable<MyData> list = dao.getAll();
		mav.addObject("datalist", list);
		return mav;
	}
// 省略

HTML

	<h1>Helo page</h1>
	<p th:text="${msg}"></p>
	<table>
		<form method="post" action="/" th:object="${formModel}">
		<tr>
			<th>ID</th><th>名前</th><th>メール</th><th>年齢</th><th>メモ(tel)</th>
		</tr>
		<tr th:each="obj: ${datalist}">
			<td th:text="${obj.id}"></td>
			<td th:text="${obj.name}"></td>
			<td th:text="${obj.mail}"></td>
			<td th:text="${obj.age}"></td>
			<td th:text="${obj.memo}"></td>
		</tr>
		</form>
	</table>

なんやとおおおおおおおおおおおおお