HibernateTest 工事中


## 参考
★https://www.javaspringclub.com/spring-mvc-hibernate-mysql-example/

## 開発環境
Tools and Environment
STS (Spring Tool Suite) (version: 3.9.10.RELEASE)
Maven (version: 3.6.2)
Java (version: 1.8.0_221)
Tomcat (version: 9.0.26)

Hibernate (version: 5.2.10.Final)
MySQL (version: 8.0.17)
Spring (version: 5.0.4.RELEASE)

spring-tool-suite-3.9.10.RELEASE-e4.13.0-win32-x86_64.zip
apache-maven-3.6.2-bin.zip
jdk-8u221-windows-x64.exe
apache-tomcat-9.0.26-windows-x64.zip
mysql-installer-web-community-8.0.17.0.msi


``` java:MainTableController
package com.exsample.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.exsample.entity.MainTable;
import com.exsample.entity.MainTableId;
import com.exsample.service.MainTableService;

import com.exsample.entity.RefTable;
import com.exsample.entity.User;

@Controller
public class MainTableController {
	// Constructor based Dependency Injection
    private MainTableService mainTableService;

	public MainTableController() {

	}

	@Autowired
	public MainTableController(MainTableService mainTableService) {
		this.mainTableService = mainTableService;
	}

	// Get All Users
	@RequestMapping(value = "/allMainTables", method = RequestMethod.POST)
	public ModelAndView displayAllMainTables() {
		System.out.println("User Page Requested : All MainTables");
		ModelAndView mv = new ModelAndView();
		
		/*
		MainTable mainTable = new MainTable();
        mainTable.addRefTable(new RefTable());
        mainTable.addRefTable(new RefTable());		
        mainTableService.saveMainTable(mainTable);
        */
		
		List<MainTable> mainTableList = mainTableService.getAllMainTables();

		for (MainTable entry : mainTableList ) {
            System.out.println("MAIN :" + entry.getId() + " : " + entry.getSubId());
            
            List<RefTable> list = entry.getRefTables();
            for(RefTable ref: list) {
                System.out.println("Sub :" + ref.getRefId() + " : " + ref.getRefSubId());
            }
        }
		
		MainTableId pk = new MainTableId(new Long(1), new Long(1));
		MainTable mainT = mainTableService.getMainTableById(pk);
		
		if (mainT != null) {
        System.out.println("MAIN :" + mainT.getId() + " : " + mainT.getSubId());
        List<RefTable> list = mainT.getRefTables();
        for(RefTable ref: list) {
            System.out.println("Sub :" + ref.getRefId() + " : " + ref.getRefSubId());
        }
        
		}
		
		List<MainTableId> keys;
		keys = new ArrayList<MainTableId>();
		
		keys.add(new MainTableId(new Long(1), new Long(1)));
		mainTableList = mainTableService.getMainTableByIds(keys);
		
		for (MainTable entry : mainTableList ) {
            System.out.println("MAIN :" + entry.getId() + " : " + entry.getSubId());
            
            List<RefTable> list = entry.getRefTables();
            for(RefTable ref: list) {
                System.out.println("Sub :" + ref.getRefId() + " : " + ref.getRefSubId());
            }
        }
		
		
		mv.addObject("mainTableList", mainTableList);
		mv.setViewName("allMainTables");
		
		return mv;
	}


	@RequestMapping(value = "/addMainTable", method = RequestMethod.GET)
	public ModelAndView displayNewUserForm() {
		ModelAndView mv = new ModelAndView("addMainTable");
		mv.addObject("headerMessage", "Add MainTable Details");
		mv.addObject("mainTable", new MainTable());
		return mv;
	}

	@RequestMapping(value = "/addMainTable", method = RequestMethod.POST)
	public ModelAndView saveNewMainTable(@ModelAttribute MainTable mainTable, BindingResult result) {
		ModelAndView mv = new ModelAndView("redirect:/home");

		if (result.hasErrors()) {
			return new ModelAndView("error");
		}
		boolean isAdded = mainTableService.saveMainTable(mainTable);
		if (isAdded) {
			mv.addObject("message", "New mainTable successfully added");
		} else {
			return new ModelAndView("error");
		}

		return mv;
	}

}


```

``` java:MainTableId
package com.exsample.entity;
// Generated 2019/10/14 14:23:33 by Hibernate Tools 5.4.3.Final

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Id;
/**
 * MainTableId generated by hbm2java
 */
@Embeddable
public class MainTableId implements java.io.Serializable {

	private Long id;
	private Long subId;

	public MainTableId() {
	}

	public MainTableId(Long id, Long subId) {
		this.id = id;
		this.subId = subId;
	}

	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getSubId() {
		return this.subId;
	}

	public void setSubId(Long subId) {
		this.subId = subId;
	}

	public boolean equals(Object other) {
		if ((this == other))
			return true;
		if ((other == null))
			return false;
		if (!(other instanceof MainTableId))
			return false;
		MainTableId castOther = (MainTableId) other;

		return (this.getId() == castOther.getId()) && (this.getSubId() == castOther.getSubId());
	}

	public int hashCode() {
		int hsCode;
		
	    hsCode = id.hashCode();
	    hsCode = 19 * hsCode+ subId.hashCode();
	    return hsCode;
	}

}
```

``` java:MainTable
package com.exsample.entity;
// Generated 2019/10/14 14:23:33 by Hibernate Tools 5.4.3.Final

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.HashSet;

import javax.persistence.Entity;
import javax.persistence.EmbeddedId;
import javax.persistence.Table;
import javax.persistence.IdClass;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.OneToMany;
import javax.persistence.FetchType;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumns;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;


// https://qiita.com/kuinaein/items/5387bdee8539da315a0f
import lombok.Data;

import com.exsample.entity.RefTable;
import com.exsample.entity.MainTableId;

/**
 * MainTable generated by hbm2java
 */
@Entity
@Table(name="MainTable")
@IdClass(MainTableId.class)
public class MainTable implements java.io.Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	@Id
	@Column(columnDefinition = "int default 1")
	private Long subId;

    @OneToMany(orphanRemoval = true, fetch = FetchType.EAGER,  cascade = CascadeType.ALL)
    @Fetch(value = FetchMode.SUBSELECT)
    @JoinColumns ({
        @JoinColumn(name="id", referencedColumnName = "id"),
        @JoinColumn(name="subId", referencedColumnName = "subId")
    })
    private List<RefTable> refTables;
    
	private String str1;
	private String str2;
	private String str3;
	private String str4;
	private String str5;
	private BigDecimal num1;
	private BigDecimal num2;
	private BigDecimal num3;
	private BigDecimal num4;
	private BigDecimal num5;
	private Date updateTime;

	public MainTable() {
		this.subId = new Long(1);
	}

	public MainTable(Long id, Long subId) {
		this.id = id;
		this.subId = subId;
	}

	public MainTable(Long id, Long subId, String str1, String str2, String str3, String str4, String str5,
			BigDecimal num1, BigDecimal num2, BigDecimal num3, BigDecimal num4, BigDecimal num5, Date updateTime) {
		this.id = id;
		this.subId = subId;
		this.str1 = str1;
		this.str2 = str2;
		this.str3 = str3;
		this.str4 = str4;
		this.str5 = str5;
		this.num1 = num1;
		this.num2 = num2;
		this.num3 = num3;
		this.num4 = num4;
		this.num5 = num5;
		this.updateTime = updateTime;
	}

	public Long getId() {
		return this.id;
	}

	public void setId(Long id) {
		this.id = id;
	}
	
	public Long getSubId() {
		return this.subId;
	}

	public void setSubId(Long subId) {
		this.subId = subId;
	}
	
	public List<RefTable> getRefTables() {
		return this.refTables;
	}

	public void setRefTables(List<RefTable> refTables) {
		this.refTables = refTables;
	}

	public String getStr1() {
		return this.str1;
	}

	public void setStr1(String str1) {
		this.str1 = str1;
	}

	public String getStr2() {
		return this.str2;
	}

	public void setStr2(String str2) {
		this.str2 = str2;
	}

	public String getStr3() {
		return this.str3;
	}

	public void setStr3(String str3) {
		this.str3 = str3;
	}

	public String getStr4() {
		return this.str4;
	}

	public void setStr4(String str4) {
		this.str4 = str4;
	}

	public String getStr5() {
		return this.str5;
	}

	public void setStr5(String str5) {
		this.str5 = str5;
	}

	public BigDecimal getNum1() {
		return this.num1;
	}

	public void setNum1(BigDecimal num1) {
		this.num1 = num1;
	}

	public BigDecimal getNum2() {
		return this.num2;
	}

	public void setNum2(BigDecimal num2) {
		this.num2 = num2;
	}

	public BigDecimal getNum3() {
		return this.num3;
	}

	public void setNum3(BigDecimal num3) {
		this.num3 = num3;
	}

	public BigDecimal getNum4() {
		return this.num4;
	}

	public void setNum4(BigDecimal num4) {
		this.num4 = num4;
	}

	public BigDecimal getNum5() {
		return this.num5;
	}

	public void setNum5(BigDecimal num5) {
		this.num5 = num5;
	}

	public Date getUpdateTime() {
		return this.updateTime;
	}

	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}

    public void addRefTable(RefTable refTable) {

        if (refTables == null ){
        	refTables = new ArrayList<RefTable>();
        }

        if (!refTables.contains(refTable))  {
        	refTables.add(refTable);
        }
    }
}

```

``` java:RefTableId 
package com.exsample.entity;
import javax.persistence.Column;
// Generated 2019/10/14 14:23:33 by Hibernate Tools 5.4.3.Final
import javax.persistence.Embeddable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;

/**
 * RefTableId generated by hbm2java
 */
@Embeddable
public class RefTableId implements java.io.Serializable {

	private Long refId;
	private Long refSubId;

	public RefTableId() {
	}

	public RefTableId(Long refId, Long refSubId) {
		this.refId = refId;
		this.refSubId = refSubId;
	}

	public Long getRefId() {
		return this.refId;
	}

	public void setRefId(Long refId) {
		this.refId = refId;
	}

	public Long getRefSubId() {
		return this.refSubId;
	}

	public void setRefSubId(Long refSubId) {
		this.refSubId = refSubId;
	}

	public boolean equals(Object other) {
		if ((this == other))
			return true;
		if ((other == null))
			return false;
		if (!(other instanceof RefTableId))
			return false;
		RefTableId castOther = (RefTableId) other;

		return (this.getRefId() == castOther.getRefId()) && (this.getRefSubId() == castOther.getRefSubId());
	}

	public int hashCode() {
		int hsCode;
	    hsCode = refId.hashCode();
	    hsCode = 19 * hsCode+ refSubId.hashCode();
	    return hsCode;
	}

}

```
``` java:RefTableId 
package com.exsample.entity;
// Generated 2019/10/14 14:23:33 by Hibernate Tools 5.4.3.Final

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.JoinTable;
import javax.persistence.Table;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import lombok.Data;

import com.exsample.entity.MainTable;
import com.exsample.entity.RefTableId;

/**
 * RefTable generated by hbm2java
 */
@Entity
@Table(name="RefTable")
@IdClass(RefTableId.class)
public class RefTable implements java.io.Serializable {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long refId;
	@Id
	@Column(columnDefinition = "int default 1")
	private Long refSubId;

	/*
    @ManyToOne
    @JoinColumns ({
        @JoinColumn(name="id", referencedColumnName = "id"),
        @JoinColumn(name="subId", referencedColumnName = "subId")
    })
    public MainTable mainTable; 
    */
	
	private String str1;
	private String str2;
	private String str3;
	private String str4;
	private String str5;
	private BigDecimal num1;
	private BigDecimal num2;
	private BigDecimal num3;
	private BigDecimal num4;
	private BigDecimal num5;
	private Date updateTime;


	public RefTable() {
		this.refSubId = new Long(1);
	}

	public RefTable(Long refId, Long refSubId) {
		this.refId = refId;
		this.refSubId = refSubId;
	}

	public RefTable(Long refId, Long refSUbId, String str1, String str2, String str3, String str4, String str5, BigDecimal num1,
			BigDecimal num2, BigDecimal num3, BigDecimal num4, BigDecimal num5, Date updateTime, Set<MainTable> mainTables) {
		this.refId = refId;
		this.refSubId = refSubId;
		
		this.str1 = str1;
		this.str2 = str2;
		this.str3 = str3;
		this.str4 = str4;
		this.str5 = str5;
		this.num1 = num1;
		this.num2 = num2;
		this.num3 = num3;
		this.num4 = num4;
		this.num5 = num5;
		this.updateTime = updateTime;
	}

	public Long getRefId() {
		return this.refId;
	}

	public void setRefId(Long refId) {
		this.refId = refId;
	}
	
	public Long getRefSubId() {
		return this.refSubId;
	}

	public void setRefSubId(Long refSubId) {
		this.refSubId = refSubId;
	}
	
	public String getStr1() {
		return this.str1;
	}

	public void setStr1(String str1) {
		this.str1 = str1;
	}

	public String getStr2() {
		return this.str2;
	}

	public void setStr2(String str2) {
		this.str2 = str2;
	}

	public String getStr3() {
		return this.str3;
	}

	public void setStr3(String str3) {
		this.str3 = str3;
	}

	public String getStr4() {
		return this.str4;
	}

	public void setStr4(String str4) {
		this.str4 = str4;
	}

	public String getStr5() {
		return this.str5;
	}

	public void setStr5(String str5) {
		this.str5 = str5;
	}

	public BigDecimal getNum1() {
		return this.num1;
	}

	public void setNum1(BigDecimal num1) {
		this.num1 = num1;
	}

	public BigDecimal getNum2() {
		return this.num2;
	}

	public void setNum2(BigDecimal num2) {
		this.num2 = num2;
	}

	public BigDecimal getNum3() {
		return this.num3;
	}

	public void setNum3(BigDecimal num3) {
		this.num3 = num3;
	}

	public BigDecimal getNum4() {
		return this.num4;
	}

	public void setNum4(BigDecimal num4) {
		this.num4 = num4;
	}

	public BigDecimal getNum5() {
		return this.num5;
	}

	public void setNum5(BigDecimal num5) {
		this.num5 = num5;
	}

	public Date getUpdateTime() {
		return this.updateTime;
	}

	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}


}

```

``` java:MainTableServiceImpl 
package com.exsample.service;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.Query;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;



import javax.persistence.TypedQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.exsample.service.MainTableService;
import com.exsample.entity.MainTable;
import com.exsample.entity.MainTableId;
import com.exsample.repository.MainTableRepository;
import com.exsample.entity.User;

@Service
@Transactional
public class MainTableServiceImpl implements MainTableService {

	  @PersistenceContext
	  private EntityManager entityManager;
	  
		// Implementing Constructor based DI
		private MainTableRepository repository;
		
		public MainTableServiceImpl() {
			
		}
		
		@Autowired
		public MainTableServiceImpl(MainTableRepository repository) {
			super();
			this.repository = repository;
		}
	
	@Override
	public List<MainTable> getAllMainTables() {
		List<MainTable> list = new ArrayList<MainTable>();
		repository.findAll().forEach(e -> list.add(e));
		return list;
	}

	@Override
	public MainTable getMainTableById(MainTableId id) {
		
		MainTable entity = entityManager.find(MainTable.class, id);
		
		return entity;
	}
	
	@Override
	public List<MainTable> getMainTableByIds(List<MainTableId> ids) {
		
		  CriteriaBuilder builder = entityManager.getCriteriaBuilder();
		    CriteriaQuery<MainTable> criteria_query = builder.createQuery(MainTable.class);
		    
		    Root<MainTable> root = criteria_query.from(MainTable.class);
		    
		    Subquery<Long> sq = criteria_query.subquery(Long.class);
		    Root<User>  tableB = sq.from(User.class);		    
		    sq.select(tableB.get("id"));
		    sq.where(builder.equal(tableB.get("id"), 3));
		    
		    criteria_query.select(root);
		    criteria_query.where( //
		    		builder.equal(root.get("id"), sq)
		    	);
		    
		    List<MainTable> list = entityManager.createQuery(criteria_query).getResultList();
		    
		   return list;
	}
	
	
	@Override
	public boolean saveMainTable(MainTable mainTable) {
		try {
			//mainTable.setId(new MainTableId(new Long(101), new Long(1)));
			//mainTable.setId(new MainTableId());
			repository.save(mainTable);
			return true;
		}catch(Exception ex) {
			return false;
		}
	}

	@Override
	public boolean deleteMainTableById(Long id, Long sub_id) {
		try {
			repository.deleteById(id);
			return true;
		}catch(Exception ex) {
			return false;
		}
		
	}

}

```

``` jsp:addMain.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home</title>
</head>
<body>
	<h1>${headerMessage}</h1>
	
        <form:form method="POST" action="addMainTable" modelAttribute="mainTable">
             <table>
                <tr>
                    <td><form:label path="str1">Str1</form:label></td>
                    <td><form:input path="str1"/></td>
                </tr>
                <tr>
                    <td><form:label path="str2">Str2</form:label></td>
                    <td><form:input path="str2"/></td>
                </tr>
                <tr>
                    <td><form:label path="num1">Num1</form:label></td>
                    <td><form:input path="num1"/></td>
                </tr>
                <tr>
                    <td><form:label path="num2">Num2</form:label></td>
                    <td><form:input path="num2"/></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Submit"/></td>
                </tr>
            </table>
        </form:form>

</body>
</html>
```

``` jsp:allMainTables
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Users</title>
</head>
<body>
	<br>
	<br>
	<br>
	<a href="${pageContext.request.contextPath}/addMainTable">Add MainTable</a>
	<br>
	<h3>List of all Tables</h3>
	${message}
	<br>
	<br>
	<table border="1px" cellpadding="0" cellspacing="0">
		<thead>
			<tr>
				<th>id</th>
				<th>subId</th>
				<th>str1</th>
				<th>str2</th>
				<th>num1</th>
				<th>num2</th>
				<th>Edit</th>
				<th>Delete</th>
			</tr>
		</thead>

		<tbody>
			<c:forEach var="mainTable" items="${mainTableList}">
				<tr>
					<td>${mainTable.id}</td>
					<td>${mainTable.subId}</td>
					<td>${mainTable.str1}</td>
					<td>${mainTable.str2}</td>
					<td>${mainTable.num1}</td>
					<td>${mainTable.num2}</td>
					<td><a
						href="${pageContext.request.contextPath}/editMainTable/${mainTable.id}">Edit</a></td>
					<td><a
						href="${pageContext.request.contextPath}/deleteMainTable/${mainTable.id}">Delete</a></td>
					<c:forEach var="refTable" items="${mainTable.refTables}">
							<td>${refTable.refId}</td>
							<td>${refTable.refSubId}</td>
							<td>${refTable.str1}</td>
							<td>${refTable.str2}</td>
							<td>${refTable.num1}</td>
							<td>${refTable.num2}</td>
					</c:forEach>
				</tr>
			</c:forEach>
		</tbody>


	</table>
</body>
</html>
```

``` jsp:home.jsp
<%@page contentType="text/html" pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>
</head>
<body>

<br>
<br>
<br>
	<form action="allMainTables" method="post">
		<input type="submit" value="List All MainTables" />
	</form>
	<form action="allUsers" method="post">
		<input type="submit" value="List All Users" />
	</form>
</body>
</html>
```

``` jsp:error
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 Something went wrong. Please try again!!
</body>
</html>
```

``` jsp:editUser
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home</title>
</head>
<body>
	<h1>${headerMessage}</h1>
	
        <form:form method="POST" action="editUser" modelAttribute="user">
        
        	<form:hidden path="id" /> 
             <table>
                <tr>
                    <td><form:label path="firstName">First Name</form:label></td>
                    <td><form:input path="firstName"/></td>
                </tr>
                <tr>
                    <td><form:label path="lastName">LastName</form:label></td>
                    <td><form:input path="lastName"/></td>
                </tr>
                <tr>
                    <td><form:label path="userName">UserName</form:label></td>
                    <td><form:input path="userName"/></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Submit"/></td>
                </tr>
            </table>
        </form:form>

</body>
</html>
```

``` application.properties
# MySQL properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:53306/exsample?serverTimezone=JST
jdbc.username=root
jdbc.password=root

# Hibernate properties
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=none
```

``` jsp:addUSer
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home</title>
</head>
<body>
	<h1>${headerMessage}</h1>
	
        <form:form method="POST" action="addUser" modelAttribute="user">
             <table>
                <tr>
                    <td><form:label path="firstName">First Name</form:label></td>
                    <td><form:input path="firstName"/></td>
                </tr>
                <tr>
                    <td><form:label path="lastName">LastName</form:label></td>
                    <td><form:input path="lastName"/></td>
                </tr>
                <tr>
                    <td><form:label path="userName">UserName</form:label></td>
                    <td><form:input path="userName"/></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Submit"/></td>
                </tr>
            </table>
        </form:form>

</body>
</html>
```

``` jsp:editUser
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home</title>
</head>
<body>
	<h1>${headerMessage}</h1>
	
        <form:form method="POST" action="editUser" modelAttribute="user">
        
        	<form:hidden path="id" /> 
             <table>
                <tr>
                    <td><form:label path="firstName">First Name</form:label></td>
                    <td><form:input path="firstName"/></td>
                </tr>
                <tr>
                    <td><form:label path="lastName">LastName</form:label></td>
                    <td><form:input path="lastName"/></td>
                </tr>
                <tr>
                    <td><form:label path="userName">UserName</form:label></td>
                    <td><form:input path="userName"/></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Submit"/></td>
                </tr>
            </table>
        </form:form>

</body>
</html>
```

``` hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="hibernate52">
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">user01</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:53306/exsample?serverTimezone=JST</property>
        <property name="hibernate.connection.username">user01</property>
        <property name="hibernate.default_catalog">exsample</property>
        <property name="hibernate.default_schema">.*</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>
```

``` hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
  <table-filter match-name=".*"/>
</hibernate-reverse-engineering>

```

``` java:HibernateConfig 
package com.exsample.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("com.exsample.repository")
@PropertySource(value = {
    "classpath:application.properties"
})
public class HibernateConfig {

    @Autowired
    private Environment environment;

    /************* Start Spring JPA config details **************/
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean() {
        LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean();
        lcemfb.setJpaVendorAdapter(getJpaVendorAdapter());
        lcemfb.setDataSource(dataSource());
        lcemfb.setPersistenceUnitName("myJpaPersistenceUnit");
        lcemfb.setPackagesToScan("com.exsample");
        lcemfb.setJpaProperties(hibernateProperties());
        return lcemfb;
    }

    @Bean
    public JpaVendorAdapter getJpaVendorAdapter() {
        JpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        return adapter;
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager txManager() {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(
            getEntityManagerFactoryBean().getObject());
        return jpaTransactionManager;
    }

    /************* End Spring JPA config details **************/

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driver"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }

}
```

``` java:ServletInitializer 
package com.exsample.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { HibernateConfig.class };
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { WebMvcConfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}

}

```

``` java:WebMvcConfig 
package com.exsample.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.exsample")
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp().prefix("/WEB-INF/views/").suffix(".jsp");
    }

}
```

``` sql:
################ MAIN, REF TABLE ##################

drop table main_ref;
drop table refTable;
drop table mainTable;


CREATE TABLE IF NOT EXISTS REFTABLE (
 refId INT AUTO_INCREMENT NOT NULL,
 refSubId INT NOT NULL DEFAULT(1),
 id INT NOT NULL,
 subId INT NOT NULL,
 str1 VARCHAR(255),
 str2 VARCHAR(255),
 str3 VARCHAR(255),
 str4 VARCHAR(255),
 str5 VARCHAR(255),
 num1 decimal(12, 2),
 num2 decimal(12, 2),
 num3 decimal(12, 2),
 num4 decimal(12, 2), 
 num5 decimal(12, 2),
 updateTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY(refId, refSubId),
 FOREIGN KEY F1(id, subId) REFERENCES MAINTABLE (id, subId)
);

INSERT INTO REFTABLE (id, subId, str1, num1) VALUE
(1,1,'b1', 1.89)
,(1,1,'b2',2.89)
,(1,1,'b3',3.89)
,(1,1,'b4',4.89)
,(1,1,'b5',5.89)
,(2,1,'b6',6.89)
,(2,1,'b7',7.89)
,(2,1,'b8',8.89)
,(3,1,'b9',9.89)
,(3,1,'b10',10.89)
;


CREATE TABLE IF NOT EXISTS MAINTABLE (
 id INT AUTO_INCREMENT NOT NULL,
 subId INT NOT NULL DEFAULT(1),
 str1 VARCHAR(255),
 str2 VARCHAR(255),
 str3 VARCHAR(255),
 str4 VARCHAR(255),
 str5 VARCHAR(255),
 num1 decimal(12, 2),
 num2 decimal(12, 2),
 num3 decimal(12, 2),
 num4 decimal(12, 2), 
 num5 decimal(12, 2),
 updateTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY(id, subId)
);


INSERT INTO MAINTABLE (str1, num1) VALUE
('a1', 1.23)
,('a2',2.23)
,('a3',3.23)
,('a4',4.23)
,('a5',5.23)
,('a6',6.23)
,('a7',7.23)
,('a8',8.23)
,('a9',9.23)
,('a10',10.23)
;

```