Spring MVC Hibernate Mysql integration CRUD example tutorial show you how to integrate Spring with Hibernate and Mysql using annotation based configuration. We will create a simple CRUD web application that permits us input user data on form and save that data in MySQL database using Hibernate, all using annotation configuration.
Other interesting posts you may like
Let’s begin step by step with the Spring MVC Hibernate Mysql integration CRUD example tutorial.
Project structure
In this Spring MVC Hibernate Mysql integration CRUD example tutorial, we will create project using maven with structure like below:
Maven Dependencies
First and foremost, we need to add dependencies in pom.xml that we are using for project, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
<?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.springmvc</groupId> <artifactId>SpringMVCHibernateExample</artifactId> <packaging>war</packaging> <name>SpringMVCHibernateExample</name> <properties> <springframework.version>4.3.0.RELEASE</springframework.version> <hibernate.version>4.3.6.Final</hibernate.version> <mysql.version>5.1.31</mysql.version> <joda-time.version>2.3</joda-time.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- jsr303 validation --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.3.Final</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- Joda-Time --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${joda-time.version}</version> </dependency> <!-- To map JodaTime with database type --> <dependency> <groupId>org.jadira.usertype</groupId> <artifactId>usertype.core</artifactId> <version>3.0.0.CR1</version> </dependency> <!-- Servlet+JSP+JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>spring-mvc-hibernate-example</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> |
Let’s deeper:
Firt thing, We are using full annotation configuration so we need to configure this plugin in order to avoid maven failure by using the declaration like below:
1 |
<failOnMissingWebXml>false</failOnMissingWebXml> |
Second thing, we will use JSR303 Validation to validate the user input. You can refer to the complete Spring MVC Form Validation Annotation Example post to get more detail.
Third thing, we need to include JSP/Servlet/Jstl dependencies to use servlet api’s and jstl view in source code. But we can set the scope as ‘provided’ for them in pom.xml because containers might already support these libraries.
The rest thing, we don’t forget Spring, Hibernate and Joda-Time dependencies.
Hibernate congfiguration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package com.javabycode.springmvc.configuration; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScan({ "com.javabycode.springmvc.configuration" }) @PropertySource(value = { "classpath:jdbc.properties" }) public class MyHibernateConfig { @Autowired private Environment environment; @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[] { "com.javabycode.springmvc.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); 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")); return properties; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory s) { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(s); return txManager; } } |
Let’s dig deeper:
@Configuration marked this class contains bean methods annotated with @Bean producing beans manageable by spring container. In this case, this class takes care hibernate configuration.
@ComponentScan is equivalent to the declaration context:component-scan base-package=”…” in xml, it indicates where spring looks for beans or classes.
@EnableTransactionManagement is equivalent to the declaration Spring’s tx:* XML namespace and enable Spring’s annotation-driven transaction management capability.
@PropertySource is used to declare a set of properties so we can configure different values in different application environments.
Method sessionFactory() is creating a LocalSessionFactoryBean, which is equivalent to the below declaration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="annotatedClasses"> <list> ... </list> </property> <property name="hibernateProperties"> <props> ... </props> </property> <property name="dataSource" ref="dataSource"></property> </bean> |
Once the SessionFactory is created, it will be injected into Bean method transactionManager which enable the support of transaction management.
Below is the properties file used in the above code snippet.
/src/main/resources/jdbc.properties
1 2 3 4 5 6 7 |
jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/javabycode jdbc.username = javabycode jdbc.password = mypassword hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.show_sql = true hibernate.format_sql = true |
Configure Spring MVC with Java Annotation Configuration
This Spring MVC configuration part was introduced in the previous tutorial, you can refer to the post Spring MVC Annotation Example. So i don’t mention it here. You can also look into the MyWebConfig class in the attachment source code.
In this post, we are working with form submission and validating user input. The “messages” properties file is used to contain messages form warning user. We have a tutorial for this topic, you can refer to the post Spring MVC Form Validation Annotation Example. You can also look into the messages.properties file in attached source code.
Configure the Dispatcher Servlet
This Configure the Dispatcher Servlet part was introduced in the previous tutorial, you can refer to the post Spring MVC Annotation Example. So i don’t mention it here. You can also look into the ServletInitializer class in the attached source code.
Create Controller
Add the controller which will serve the GET and POST request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
package com.javabycode.springmvc.controller; import java.util.List; import java.util.Locale; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.javabycode.springmvc.model.Student; import com.javabycode.springmvc.service.StudentService; @Controller @RequestMapping("/") public class MyController { @Autowired StudentService service; @Autowired MessageSource messageSource; /* * List all existing Students. */ @RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET) public String listStudents(ModelMap model) { List<Student> students = service.findAllStudents(); model.addAttribute("students", students); return "allstudents"; } /* * Add a new Student. */ @RequestMapping(value = { "/new" }, method = RequestMethod.GET) public String newStudent(ModelMap model) { Student student = new Student(); model.addAttribute("student", student); model.addAttribute("edit", false); return "registration"; } /* * Handling POST request for validating the user input and saving Student in database. */ @RequestMapping(value = { "/new" }, method = RequestMethod.POST) public String saveStudent(@Valid Student student, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "registration"; } if(!service.isStudentCodeUnique(student.getId(), student.getCode())){ FieldError codeError =new FieldError("Student","code",messageSource.getMessage("non.unique.code", new String[]{student.getCode()}, Locale.getDefault())); result.addError(codeError); return "registration"; } service.saveStudent(student); model.addAttribute("success", "Student " + student.getName() + " registered successfully"); return "success"; } /* * Provide the existing Student for updating. */ @RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.GET) public String editStudent(@PathVariable String code, ModelMap model) { Student student = service.findStudentByCode(code); model.addAttribute("student", student); model.addAttribute("edit", true); return "registration"; } /* * Handling POST request for validating the user input and updating Student in database. */ @RequestMapping(value = { "/edit-{code}-student" }, method = RequestMethod.POST) public String updateStudent(@Valid Student student, BindingResult result, ModelMap model, @PathVariable String code) { if (result.hasErrors()) { return "registration"; } if(!service.isStudentCodeUnique(student.getId(), student.getCode())){ FieldError codeError =new FieldError("Student","code",messageSource.getMessage("non.unique.code", new String[]{student.getCode()}, Locale.getDefault())); result.addError(codeError); return "registration"; } service.updateStudent(student); model.addAttribute("success", "Student " + student.getName() + " updated successfully"); return "success"; } /* * Delete an Student by it's CODE value. */ @RequestMapping(value = { "/delete-{code}-student" }, method = RequestMethod.GET) public String deleteStudent(@PathVariable String code) { service.deleteStudentByCode(code); return "redirect:/list"; } } |
Let’s dig deeper:
@Controller annotation marked this MyController class is a controller that handle the requests with pattern ‘/’ mapped by @RequestMapping.
Method listStudents is annotated with @RequestMethod.GET and handle the requests with both pattern ‘/’ and ‘/list’. It takes care for initial page of application, showing a list of existing students
Method newStudent handle the GET request for the new student registration page.
Method saveStudent will handle the form-submission POST requests – pattern ‘/new’ for new student registration. @Valid asks spring framework to validate the associated object(Student) following the JSR303 Validation standard. BindingResult receives the outcome of this validation and any error that might have occurred during this validation. In case of validation failure, error messages will be shown.
Method editStudent brings you to the registration page that is filled up student details, while updateStudent will be invoked when you click on update button.
Method deleteStudent takes care the deletion of an student by CODE. Notice @PathVariable, which bind its parameter to variable in URI template.
The above stuffs are all we need to do for Annotation based configuration. We will add layer, dao layer, views, domain object, database schema and run the application.
Add DAO Layer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.javabycode.springmvc.dao; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; public abstract class AbstractDao<PK extends Serializable, T> { private final Class<T> persistentClass; @SuppressWarnings("unchecked") public AbstractDao(){ this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; } @Autowired private SessionFactory sessionFactory; protected Session getSession(){ return sessionFactory.getCurrentSession(); } @SuppressWarnings("unchecked") public T getByKey(PK key) { return (T) getSession().get(persistentClass, key); } public void persist(T entity) { getSession().persist(entity); } public void delete(T entity) { getSession().delete(entity); } protected Criteria createEntityCriteria(){ return getSession().createCriteria(persistentClass); } } |
This AbstractDao class is the base class for all DAO implementation classes. It provides the wrapper methods for common hibernate operations. Here, we are injecting the SessionFactory that is mentioned in above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javabycode.springmvc.dao; import java.util.List; import com.javabycode.springmvc.model.Student; public interface StudentDao { Student findById(int id); void saveStudent(Student student); void deleteStudentByCode(String ssn); List<Student> findAllStudents(); Student findStudentByCode(String ssn); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package com.javabycode.springmvc.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import com.javabycode.springmvc.model.Student; @Repository("studentDao") public class StudentDaoImpl extends AbstractDao<Integer, Student> implements StudentDao { public Student findById(int id) { return getByKey(id); } public void saveStudent(Student student) { persist(student); } public void deleteStudentByCode(String code) { Query query = getSession().createSQLQuery("delete from Student where code = :code"); query.setString("code", code); query.executeUpdate(); } @SuppressWarnings("unchecked") public List<Student> findAllStudents() { Criteria criteria = createEntityCriteria(); return (List<Student>) criteria.list(); } public Student findStudentByCode(String code) { Criteria criteria = createEntityCriteria(); criteria.add(Restrictions.eq("code", code)); return (Student) criteria.uniqueResult(); } } |
Add Service Layer
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.javabycode.springmvc.service; import java.util.List; import com.javabycode.springmvc.model.Student; public interface StudentService { Student findById(int id); void saveStudent(Student student); void updateStudent(Student student); void deleteStudentByCode(String code); List<Student> findAllStudents(); Student findStudentByCode(String code); boolean isStudentCodeUnique(Integer id, String code); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package com.javabycode.springmvc.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.javabycode.springmvc.dao.StudentDao; import com.javabycode.springmvc.model.Student; @Service("studentService") @Transactional public class StudentServiceImpl implements StudentService { @Autowired private StudentDao dao; public Student findById(int id) { return dao.findById(id); } public void saveStudent(Student student) { dao.saveStudent(student); } public void updateStudent(Student student) { Student entity = dao.findById(student.getId()); if(entity!=null){ entity.setName(student.getName()); entity.setEnteringDate(student.getEnteringDate()); entity.setNationality(student.getNationality()); entity.setCode(student.getCode()); dao.saveStudent(student); } } public void deleteStudentByCode(String ssn) { dao.deleteStudentByCode(ssn); } public List<Student> findAllStudents() { return dao.findAllStudents(); } public Student findStudentByCode(String ssn) { return dao.findStudentByCode(ssn); } public boolean isStudentCodeUnique(Integer id, String ssn) { Student student = findStudentByCode(ssn); return ( student == null || ((id != null) && (student.getId() == id))); } } |
Most interesting part above is @Transactional which starts a transaction on each method start, and commits it on each method exit ( or rollback if method was failed due to an error). Note that since the transaction are on method scope, and inside method we are using DAO, DAO method will be executed within same transaction.
Create Entity Class(POJO)
In this Spring MVC Hibernate Mysql integration CRUD example tutorial, we create the actual Student Entity like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
package com.javabycode.springmvc.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.annotations.Type; import org.hibernate.validator.constraints.NotEmpty; import org.joda.time.LocalDate; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="student") public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Size(min=3, max=50) @Column(name = "NAME", nullable = false) private String name; @NotNull @DateTimeFormat(pattern="dd/MM/yyyy") @Column(name = "ENTERING_DATE", nullable = false) @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate") private LocalDate enteringDate; @NotNull @Column(name = "nationality", nullable = false) private String nationality; @NotEmpty @Column(name = "CODE", unique=true, nullable = false) private String code; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setCode(String code) { this.code = code; } public void setEnteringDate(LocalDate enteringDate) { this.enteringDate = enteringDate; } public void setNationality(String nationality) { this.nationality = nationality; } public String getCode() { return code; } public LocalDate getEnteringDate() { return enteringDate; } public String getNationality() { return nationality; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Student)) return false; Student other = (Student) obj; if (id != other.id) return false; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", enteringDate=" + enteringDate + ", nationality=" + nationality + ", code=" + code + "]"; } } |
The above is a standard Entity class annotated with JPA annotations @Entity, @Table, @Column. One more, hibernate specific annotation @Type are using to map between database date type and Joda-Time LocalDate.
@DateTimeFormat is a specific annotation which indicates that a field should be formatted as a date time with a give format.
Rest of annotations are validation related JSR303 API, you also get more about it via the post Spring MVC Form Validation Annotation Example
Add Views
allstudents.jsp is a page that contain list of all existing students
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>List of Students</title> </head> <body> <h2>List of Students</h2> <table> <tr> <td>NAME</td><td>Entering Date</td><td>Nationality</td><td>CODE</td><td></td> </tr> <c:forEach items="${students}" var="student"> <tr> <td>${student.name}</td> <td>${student.enteringDate}</td> <td>${student.nationality}</td> <td><a href="<c:url value='/edit-${student.code}-student' />">${student.code}</a></td> <td><a href="<c:url value='/delete-${student.code}-student' />">delete</a></td> </tr> </c:forEach> </table> <br/> <a href="<c:url value='/new' />">Add New Student</a> </body> </html> |
registration.jsp is a registration page to create and save new student
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Student Registration Form</title> </head> <body> <h2>Registration Form</h2> <form:form method="POST" modelAttribute="student"> <form:input type="hidden" path="id" id="id"/> <table> <tr> <td><label for="name">Name: </label> </td> <td><form:input path="name" id="name"/></td> <td><form:errors path="name" cssClass="error"/></td> </tr> <tr> <td><label for="enteringDate">Entering Date: </label> </td> <td><form:input path="enteringDate" id="enteringDate"/></td> <td><form:errors path="enteringDate" cssClass="error"/></td> </tr> <tr> <td><label for="nationality">Nationality: </label> </td> <td><form:input path="nationality" id="nationality"/></td> <td><form:errors path="nationality" cssClass="error"/></td> </tr> <tr> <td><label for="code">CODE: </label> </td> <td><form:input path="code" id="code"/></td> <td><form:errors path="code" cssClass="error"/></td> </tr> <tr> <td colspan="3"> <c:choose> <c:when test="${edit}"> <input type="submit" value="Update"/> </c:when> <c:otherwise> <input type="submit" value="Register"/> </c:otherwise> </c:choose> </td> </tr> </table> </form:form> <br/> <br/> Go back to <a href="<c:url value='/list' />">List of All Students</a> </body> </html> |
success.jsp is a success page with confirmation of new student creation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Registration Confirmation Page</title> </head> <body> message : ${success} <br/> <br/> Go back to <a href="<c:url value='/list' />">List of All Students</a> </body> </html> |
Create Schema in database
1 2 3 4 5 6 7 8 |
CREATE TABLE STUDENT( id INT NOT NULL auto_increment, name TEXT NOT NULL, entering_date DATE NOT NULL, natinality TEXT NOT NULL, code VARCHAR(30) NOT NULL UNIQUE, PRIMARY KEY (id) ); |
If MySQL installation is a problem with you, you can search MySQL installation on Local PC on google or download XAMPP that is just packaged with Mysql.
Build, deploy and Run Application
Now we can build war file by using eclipse or maven command line. Since here we are using Tomcat such as Servlet container and we put this war file into tomcat webapps folder then start tomcat. Access the address http://localhost:8080/spring-mvc-hibernate-example and the screen will display like this:
Add new student by clicking the link “Add New Student” and enter information of student, for example:
Then click the Register button to insert student data into database. Back to the “List of All Students” screen, we see that student.
Now we can update the student information that we just register on the above step by clicking the link in the CODE column on the “List of All Students” screen. It brings you to the update screen like this:
Change the entering date and nationality of student and click the update button. Beside, we can delete a student by clicking its delete link.
That’s it on the Spring MVC Hibernate Mysql integration CRUD example tutorial
Downlaod complete source code of example, please click link below
SpringMVCHibernateExample.zip (871 downloads)
Can you help me fix this error?
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (default-compile) on project SpringMVCHibernateExample: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
Here is common error. Fix this following steps:
1. On your Eclipse IDE, go into Window > Preferences > Java > Installed JREs > and check your installed JREs. You should have an entry with a JDK there.
2. Select the Execution Env as show below. Click OK
3. Then Right-Click on your Project -> Maven -> Update Project
Can you please tell me how do i run this code on IntelliJ IDE?