SQLクエリーに似た簡易言語
本格的な検索処理はJPQLを理解する必要がある
1.EntityManagerの用意
2.Queryの作成
3.結果(List)の取得
html
<table> <form action="/find" method="post"> <tr> <td>FIND:</td> <td><input type="text" name="fstr" size="20" th:value="${value}"></td></td> </tr> <tr> <td></td> <td><input type="submit"></td> </tr> </form> </table>
controller
@RequestMapping(value="/find", method=RequestMethod.GET) public ModelAndView find(ModelAndView mav) { mav.setViewName("find"); mav.addObject("title", "Find Page"); mav.addObject("msg","MyData sample"); mav.addObject("value", ""); Iterable<MyData> list = dao.getAll(); mav.addObject("datalist", list); return mav; } @RequestMapping(value="/find", method=RequestMethod.POST) public ModelAndView search(HttpServletRequest request, ModelAndView mav) { mav.setViewName("find"); String param = request.getParameter("fstr"); if(param =="") { mav = new ModelAndView("redirect:/find"); } else { mav.addObject("title","Find result"); mav.addObject("msg","「" + param + "」の検索結果"); mav.addObject("value", param); List<MyData> list = dao.find(param); mav.addObject("datalist", list); } return mav; }
MyDataDao
public interface MyDataDao <T> extends Serializable { public List<T> getAll(); public T findById(long id); public List<T> findByName(String name); public List<T> find(String fstr); }
@Override public List<MyData> find(String fstr){ List<MyData> list = null; String qstr = "from MyData where id = :fstr"; Query query = entityManager.createQuery(qstr).setParameter("fstr", Long.parseLong(fstr)); list = query.getResultList(); return list; }