html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<title th:text="${title}">top page</title>
	<meta http-equiv="Content-Type" 
		content="text/html; charset=UTF-8" />
	<style>
	h1 { font-size:18pt; font-weight:bold; color:gray; }
	body { font-size:13pt; color:gray; margin:5px 25px; }
	tr { margin:5px; }
	th { padding:5px; color:white; background:darkgray; }
	td { padding:5px; color:black; background:#f0f0f0; }
	</style>
</head>
<body>
	<h1 th:text="${title}">MyMsg page</h1>
	<p th:text="${msg}"></p>
	<table>
	<form method="post" action="/msg" 
			th:object="${formModel}" id="myform">
	<!-- 	<input type="hidden" name="mydata_id" th:value="*{mydata_id}" id="myform" /> -->
		<tr><td><label for="title">タイトル</label></td>
			<td><input type="text" name="title" 
				th:value="*{title}"  form="myform" /></td></tr>
		<tr><td><label for="message">メッセージ</label></td>
			<td><textarea name="message"  
				th:text="*{message}" form="myform"></textarea></td></tr>
		<tr><td><label for="mydata">MYDATA_ID</label></td>
			<td><input type="text" name="mydata_id" form="myform" /></td></tr>
		<tr><td></td><td><input type="submit" /></td></tr>
	</form>
	</table>
	<hr/>
			<form method="post" action="/search">
			
			<!-- <form method="post" th:action="@{'/search/' + @{param.sorting[0]} + @{param.order[0]}}">-->		
			
			<input type="text" name="kw" th:value="${kw}" />
		<input type="submit" value="検索" />
	</form>
	<table>
	<tr><th>ID</th><th>メッセージ</th><th>タイトル</th></tr>
	<tr th:each="obj : ${datalist}">
		<td><a th:text="${obj.mydata_id}" th:href="@{/sorting(id=${obj.mydata_id})}"></a></td>
		<td th:text="${obj.mydata.name}"></td>
		<td th:text="${obj.title}"></td>
	</tr>
	</table>
</body>
</html>





■Controller

package com.tuyano.springboot;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tuyano.springboot.repositories.MsgDataRepository;

@Controller
public class MsgDataController {
	private static final Logger logger = LoggerFactory.getLogger(MsgDataController.class);
	@Autowired
	MsgDataRepository repository;
	
	@PersistenceContext
	EntityManager entityManager;
	
	MsgDataDaoImpl dao;
	
	/**
	 * ソート付き一覧表示
	 * @param mav
	 * @param sorting
	 * @param order
	 * @param pagable
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView msg(
			ModelAndView mav,
			@RequestParam("sorting") String sorting,
			@RequestParam("order")   String order,
			Pageable pagable
			) {
        logger.info("Called getWhiskies.");
        logger.info(sorting);
        logger.info(order);
		mav.setViewName("showMsgData");
		mav.addObject("title","Sample");
		mav.addObject("msg","MsgDataのサンプルです。");
		MsgData msgdata = new MsgData();
		mav.addObject("formModel", msgdata);
		List<MsgData> list = dao.getAll(sorting, order);
//		Page<MsgData> list = dao.getAll(sorting, order, pagable);
		mav.addObject("datalist", list);
		return mav;
	}

	/**
	 * フォームからINSERT処理
	 * @param msgdata
	 * @param result
	 * @param mav
	 * @return
	 */
	@RequestMapping(value = "/msg", method = RequestMethod.POST)
	public ModelAndView msgform(
			@Valid @ModelAttribute MsgData msgdata,
			Errors result, 
			ModelAndView mav) {
		if (result.hasErrors()) {
			mav.setViewName("showMsgData");
			mav.addObject("title", "Sample [ERROR]");
			mav.addObject("msg", "値を再チェックしてください!");
			return mav;
		} else {
			repository.saveAndFlush(msgdata);
			return new ModelAndView("redirect:/msg");
		}
	}

	/**
	 *  検索用
	 * @param kw
	 * @param mav
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public ModelAndView search(
//			@Valid @ModelAttribute MsgData msgdata,
			@RequestParam("kw") String kw,
			ModelAndView mav) {
        logger.info("reeeeeeeeeergverkmhrthmrtphgkフォ@gジェオpjth");
        logger.info(kw);
			mav.setViewName("showMsgData");
			mav.addObject("kw", kw);
			MsgData msgdata = new MsgData();
			mav.addObject("formModel", msgdata);
			List<MsgData> list = dao.search(kw);
			mav.addObject("datalist", list);
			return mav;
	}
//	@RequestMapping(value = "/sorting", method = RequestMethod.GET)
//	public ModelAndView sorting(
//			@RequestParam("sorting") String sorting,
//			ModelAndView mav) {
//			List<MsgData> list = dao.getAll("title");
//			return new ModelAndView("redirect:/msg");
//	}

	@PostConstruct
	public void init(){
		System.out.println("ok");
		dao = new MsgDataDaoImpl(entityManager);
	}
}






■yml

spring:
  datasource:
    url: jdbc:mysql://localhost/test
    username: Owner
    password: 
    driverClassName: com.mysql.jdbc.Driver
logging:
    file: logs/myapp.log
    level:
        org.springframework.web: INFO
        org:
            hibernate:
                SQL: DEBUG
                type:
                    descriptor:
                        sql:
                            BasicBinder: TRACE



■Entity

package com.tuyano.springboot;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

@Entity
@Table(name="goods")
public class MyData {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column
	@NotNull
	private	long id;
	
	@Column(length = 50, nullable = false)
	private String name;
	
	@Column(length = 200, nullable = true)
	private String mail;
	
//	@Column(nullable = true)
//	private Integer age;
	
	@Column(nullable = true)
	private String memo;
	
	@OneToMany(cascade=CascadeType.ALL)
	@Column(nullable = true)
	private List<MsgData> msgdatas;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMail() {
		return mail;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
//	public Integer getAge() {
//		return age;
//	}
//	public void setAge(Integer age) {
//		this.age = age;
//	}
	public String getMemo() {
		return memo;
	}
	public void setMemo(String memo) {
		this.memo = memo;
	}
	public List<MsgData> getMsgdatas() {
		return msgdatas;
	}

	public void setMsgdatas(List<MsgData> msgdatas) {
		this.msgdatas = msgdatas;
	}
}



-----------------------------------------------------------------------------------------------------------------------

package com.tuyano.springboot;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name = "msgdata")
public class MsgData {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column
	@NotNull
	private long mydata_id;

	@Column
	private String title;

	@Column(nullable = false)
	private String message;

	@ManyToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
	@JoinColumn(name="mydata_id",referencedColumnName="id", insertable=false, updatable=false)
	private MyData mydata;

	public MsgData() {
		super();
		mydata = new MyData();
	}

	public MyData getMydata() {
		return mydata;
	}
	
	public long getMydata_id() {
		return mydata_id;
	}

	public void setMydata_id(long mydata_id) {
		this.mydata_id = mydata_id;
	}
	
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void setMydata(MyData mydata) {
		this.mydata = mydata;
	}
}






■インターフェーす

package com.tuyano.springboot;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

public interface MsgDataDao<T> {
	public List<MsgData> getAll();
	// ソート用(仮にStringに全部変換してやるけど、多分ジェネリクスでできる)
	public List<MsgData> getAll(String sort_param, String order);
//	public Page<MsgData> getAll(String sort_param, String order, Pageable pagable);
	//検索用
	public List<MsgData> search(String kw);
//	
//	public MsgData findById(long id);
//	public List<MsgData> findByName(String name);
}


■Impl実装クラス

package com.tuyano.springboot;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;
import com.tuyano.springboot.MsgData;

@SuppressWarnings("rawtypes")
@Repository
public class MsgDataDaoImpl implements MsgDataDao<MsgDataDao> {
	private EntityManager entityManager;

	public MsgDataDaoImpl() {
		super();
	}
	
	public MsgDataDaoImpl(EntityManager manager) {
		entityManager = manager;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MsgData> getAll() {
		return entityManager
				.createQuery("from MsgData")
				.getResultList();
	}
	
	// ソートによる一覧処理
	@SuppressWarnings("unchecked")
	@Override
	public List<MsgData> getAll(String sorting, String order_str) {
//	public Page<MsgData> getAll(String sorting, String order, Pageable pagable) {
		List<MsgData> list = null;
		//BUilderの取得
		CriteriaBuilder builder = entityManager.getCriteriaBuilder();
		//クエリの生成
		CriteriaQuery<MsgData> query = builder.createQuery(MsgData.class);
		//Rootクラスインスタンスの生成
		Root<MsgData> root = query.from(MsgData.class);
		String asc = "asc";
		
		//sorting
		if (order_str != "") {
//			String order = asc.equals(order_str) ? "asc" : order_str;
			if(asc.equals(order_str)) {
				//指定の文字列でsorting by asc
				query.select(root).orderBy(builder.asc(root.get(sorting)));
			}else {
				//by desc
				query.select(root).orderBy(builder.desc(root.get(sorting)));
			}
		}
		
//		list =  (Page<MsgData>) entityManager.createQuery(query).getResultList();
		list =  entityManager.createQuery(query).getResultList();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<MsgData> search(String kw) {
		List<MsgData> list = null;
		String qstr = "from MsgData "
				+ "where mydata_id like :fid "
				+ " or title like :fname"
				+ " or message like :fmessage";
		Long fid = 0L;
		try {
			fid = Long.parseLong(kw);
		}catch(NumberFormatException e){
			e.printStackTrace();
		}
		//https://teratail.com/questions/3300
//		if(isNumber(kw)){
			//検索KWがIDの場合 IDはlong その他はStringで検索
//				Query query = entityManager.createQuery(qstr).setParameter("fid", fid)
//				.setParameter("fname", "%" + kw + "%")
//				.setParameter("fmessage", kw + "%");
//		}
//		else{
//			Query query = entityManager.createQuery(qstr).setParameter("fid", fid)
//			.setParameter("fname", "%" + kw + "%")
//			.setParameter("fmessage", kw + "%");
//		}
		
		Query query = entityManager.createQuery(qstr).setParameter("fid", fid)
				.setParameter("fname", "%" + kw + "%")
				.setParameter("fmessage", kw + "%");
		list = query.getResultList();
		return list;
	}
	
//	// KWがlongかStringかをパース前に判定する
//	public boolean isNumber(String num) {
//	    try {
//	    		fid =Long.parseLong(num);
//		        return true;
//	        } catch (NumberFormatException e) {
//		        return false;
//	    }
//	}
	
//	@SuppressWarnings("unchecked")
//	@Override
//	public List<MsgData> getAll(String sort_param) {
//		List<MsgData> list = null;
//		//BUilderの取得
//		CriteriaBuilder builder = entityManager.getCriteriaBuilder();
//		//クエリの生成
//		CriteriaQuery<MsgData> query = builder.createQuery(MsgData.class);
//		//Rootクラスインスタンスの生成
//		Root<MsgData> root = query.from(MsgData.class);
//		//指定の文字列でsorting
//		query.select(root).orderBy(builder.desc(root.get(sort_param)));
//		list = entityManager.createQuery(query).getResultList();
//		return list;
//	}
	
//	@Override
//	public MsgData findById(long mydata_id) {
//		return (MsgData)entityManager
//				.createQuery("from MsgData where id = " 
//				+ mydata_id).getSingleResult();
//	}
//
//	@SuppressWarnings("unchecked")
//	@Override
//	public List<MsgData> findByName(String name) {
//		return (List<MsgData>)entityManager
//				.createQuery("from MsgData where name = " 
//				+ name).getSingleResult();
//	}
}