Spring MVC Hibernate MySQL Integration(集成) CRUD Example Tutorial

We learned how to integrate Spring and Hibernate in our last tutorial(教程). Today we will move forward and integrate Spring MVC and Hibernate frameworks in a web application CRUD example.

Our final project structure(结构) looks like below image, we will look into each of the components(组件) one by one.

Spring-MVC-Hibernate-Example

Note that I am using Spring 4.0.3.Release and Hibernate 4.3.5.Final versions for our example, same program is also compatible(兼容) for Spring 4 and Hibernate 3, however you need to make small changes in spring bean configuration file discussed in the last tutorial.

Maven Dependencies(maven依赖关系)

Let’s look at all the maven dependencies are required for hibernate and spring mvc framework integration.

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.journaldev.spring</groupId>
  6. <artifactId>SpringMVCHibernate</artifactId>
  7. <name>SpringMVCHibernate</name>
  8. <packaging>war</packaging>
  9. <version>1.0.0-BUILD-SNAPSHOT</version>
  10. <properties>
  11. <java-version>1.6</java-version>
  12. <org.springframework-version>4.0.3.RELEASE</org.springframework-version>
  13. <org.aspectj-version>1.7.4</org.aspectj-version>
  14. <org.slf4j-version>1.7.5</org.slf4j-version>
  15. <hibernate.version>4.3.5.Final</hibernate.version>
  16. </properties>
  17. <dependencies>
  18. <!-- Spring -->
  19. <dependency>
  20. <groupId>org.springframework</groupId>
  21. <artifactId>spring-context</artifactId>
  22. <version>${org.springframework-version}</version>
  23. <exclusions>
  24. <!-- Exclude Commons Logging in favor of SLF4j -->
  25. <exclusion>
  26. <groupId>commons-logging</groupId>
  27. <artifactId>commons-logging</artifactId>
  28. </exclusion>
  29. </exclusions>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework</groupId>
  33. <artifactId>spring-webmvc</artifactId>
  34. <version>${org.springframework-version}</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework</groupId>
  38. <artifactId>spring-tx</artifactId>
  39. <version>${org.springframework-version}</version>
  40. </dependency>
  41. <!-- Hibernate -->
  42. <dependency>
  43. <groupId>org.hibernate</groupId>
  44. <artifactId>hibernate-core</artifactId>
  45. <version>${hibernate.version}</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.hibernate</groupId>
  49. <artifactId>hibernate-entitymanager</artifactId>
  50. <version>${hibernate.version}</version>
  51. </dependency>
  52. <!-- Apache Commons DBCP -->
  53. <dependency>
  54. <groupId>commons-dbcp</groupId>
  55. <artifactId>commons-dbcp</artifactId>
  56. <version>1.4</version>
  57. </dependency>
  58. <!-- Spring ORM -->
  59. <dependency>
  60. <groupId>org.springframework</groupId>
  61. <artifactId>spring-orm</artifactId>
  62. <version>${org.springframework-version}</version>
  63. </dependency>
  64. <!-- AspectJ -->
  65. <dependency>
  66. <groupId>org.aspectj</groupId>
  67. <artifactId>aspectjrt</artifactId>
  68. <version>${org.aspectj-version}</version>
  69. </dependency>
  70. <!-- Logging -->
  71. <dependency>
  72. <groupId>org.slf4j</groupId>
  73. <artifactId>slf4j-api</artifactId>
  74. <version>${org.slf4j-version}</version>
  75. </dependency>
  76. <dependency>
  77. <groupId>org.slf4j</groupId>
  78. <artifactId>jcl-over-slf4j</artifactId>
  79. <version>${org.slf4j-version}</version>
  80. <scope>runtime</scope>
  81. </dependency>
  82. <dependency>
  83. <groupId>org.slf4j</groupId>
  84. <artifactId>slf4j-log4j12</artifactId>
  85. <version>${org.slf4j-version}</version>
  86. <scope>runtime</scope>
  87. </dependency>
  88. <dependency>
  89. <groupId>log4j</groupId>
  90. <artifactId>log4j</artifactId>
  91. <version>1.2.15</version>
  92. <exclusions>
  93. <exclusion>
  94. <groupId>javax.mail</groupId>
  95. <artifactId>mail</artifactId>
  96. </exclusion>
  97. <exclusion>
  98. <groupId>javax.jms</groupId>
  99. <artifactId>jms</artifactId>
  100. </exclusion>
  101. <exclusion>
  102. <groupId>com.sun.jdmk</groupId>
  103. <artifactId>jmxtools</artifactId>
  104. </exclusion>
  105. <exclusion>
  106. <groupId>com.sun.jmx</groupId>
  107. <artifactId>jmxri</artifactId>
  108. </exclusion>
  109. </exclusions>
  110. <scope>runtime</scope>
  111. </dependency>
  112. <!-- @Inject -->
  113. <dependency>
  114. <groupId>javax.inject</groupId>
  115. <artifactId>javax.inject</artifactId>
  116. <version>1</version>
  117. </dependency>
  118. <!-- Servlet -->
  119. <dependency>
  120. <groupId>javax.servlet</groupId>
  121. <artifactId>servlet-api</artifactId>
  122. <version>2.5</version>
  123. <scope>provided</scope>
  124. </dependency>
  125. <dependency>
  126. <groupId>javax.servlet.jsp</groupId>
  127. <artifactId>jsp-api</artifactId>
  128. <version>2.1</version>
  129. <scope>provided</scope>
  130. </dependency>
  131. <dependency>
  132. <groupId>javax.servlet</groupId>
  133. <artifactId>jstl</artifactId>
  134. <version>1.2</version>
  135. </dependency>
  136. <!-- Test -->
  137. <dependency>
  138. <groupId>junit</groupId>
  139. <artifactId>junit</artifactId>
  140. <version>4.7</version>
  141. <scope>test</scope>
  142. </dependency>
  143. </dependencies>
  144. <build>
  145. <plugins>
  146. <plugin>
  147. <artifactId>maven-eclipse-plugin</artifactId>
  148. <version>2.9</version>
  149. <configuration>
  150. <additionalProjectnatures>
  151. <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
  152. </additionalProjectnatures>
  153. <additionalBuildcommands>
  154. <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
  155. </additionalBuildcommands>
  156. <downloadSources>true</downloadSources>
  157. <downloadJavadocs>true</downloadJavadocs>
  158. </configuration>
  159. </plugin>
  160. <plugin>
  161. <groupId>org.apache.maven.plugins</groupId>
  162. <artifactId>maven-compiler-plugin</artifactId>
  163. <version>2.5.1</version>
  164. <configuration>
  165. <source>1.6</source>
  166. <target>1.6</target>
  167. <compilerArgument>-Xlint:all</compilerArgument>
  168. <showWarnings>true</showWarnings>
  169. <showDeprecation>true</showDeprecation>
  170. </configuration>
  171. </plugin>
  172. <plugin>
  173. <groupId>org.codehaus.mojo</groupId>
  174. <artifactId>exec-maven-plugin</artifactId>
  175. <version>1.2.1</version>
  176. <configuration>
  177. <mainClass>org.test.int1.Main</mainClass>
  178. </configuration>
  179. </plugin>
  180. </plugins>
  181. <finalName>${project.artifactId}</finalName>
  182. </build>
  183. </project>

Some of the dependencies above are included by STS (Spring Tool Suite) when I create Spring MVC project. Important dependencies above are spring-context, spring-webmvc, spring-tx, hibernate-core, hibernate-entitymanager and spring-orm. I am using Apache Commons DBCP for connection pooling, but in real life situations, most probably you have connection pooling done by the container and all we need is to provide the JNDI reference details to use.

NOTE: I noticed that some of the readers are getting database connection issues. Notice that in my pom.xml, there is no database driver. That works for me because I have MySQL driver in tomcat lib directory and some DataSource connections configured with it. For any database connection related issues, either put the database driver in container lib or include that in pom.xml dependencies.

Deployment Descriptor(部署描述符)

We need to plugin spring framework in our web application, that is done by configuring (配置)Spring framework DispatcherServlet as front controller. Our web.xml file looks like below.

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  1. <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
  2. <context-param>
  3. <param-name>contextConfigLocation</param-name>
  4. <param-value>/WEB-INF/spring/root-context.xml</param-value>
  5. </context-param>
  6. <!-- Creates the Spring Container shared by all Servlets and Filters -->
  7. <listener>
  8. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  9. </listener>
  10. <!-- Processes application requests -->
  11. <servlet>
  12. <servlet-name>appServlet</servlet-name>
  13. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  14. <init-param>
  15. <param-name>contextConfigLocation</param-name>
  16. <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
  17. </init-param>
  18. <load-on-startup>1</load-on-startup>
  19. </servlet>
  20. <servlet-mapping>
  21. <servlet-name>appServlet</servlet-name>
  22. <url-pattern>/</url-pattern>
  23. </servlet-mapping>

Most of the part is boiler plate code(样板代码), most important part is the spring context file location where we will configure our spring beans and services. If you want, you can change them according to your project requirements.

Hibernate Entity Bean

We are using JPA annotations(JPA注解) in our entity bean class, however we can also have a simple java bean and mapping details in the xml file. In that case, we need to provide mapping file details while configuring Hibernate SessionFactory in spring bean configurations.

Person.java

  1. package com.journaldev.spring.model;
  2. import javax.persistence.Column;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.GenerationType;
  6. import javax.persistence.Id;
  7. import javax.persistence.Table;
  8. /**
  9. * Entity bean with JPA annotations
  10. * Hibernate provides JPA implementation
  11. * @author pankaj
  12. *
  13. */
  14. @Entity
  15. @Table(name="PERSON")
  16. public class Person {
  17. @Id
  18. @Column(name="id")
  19. @GeneratedValue(strategy=GenerationType.IDENTITY)
  20. private int id;
  21. private String name;
  22. private String country;
  23. public int getId() {
  24. return id;
  25. }
  26. public void setId(int id) {
  27. this.id = id;
  28. }
  29. public String getName() {
  30. return name;
  31. }
  32. public void setName(String name) {
  33. this.name = name;
  34. }
  35. public String getCountry() {
  36. return country;
  37. }
  38. public void setCountry(String country) {
  39. this.country = country;
  40. }
  41. @Override
  42. public String toString(){
  43. return "id="+id+", name="+name+", country="+country;
  44. }
  45. }

Our entity bean maps to PERSON table in MySQL database, notice that I have not annotated “name” and “country” fields with @Column annotation because they are of same name. Below SQL script shows the table details.

person.sql

  1. CREATE TABLE `Person` (
  2. `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(20) NOT NULL DEFAULT '',
  4. `country` varchar(20) DEFAULT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Hibernate DAO Implementation(实现)

We will create PersonDAO interface to declare the methods that we will use in our project. Next, we will provide hibernate specific(具体) implementation for it.(接口)

PersonDAO.java

  1. package com.journaldev.spring.dao;
  2. import java.util.List;
  3. import com.journaldev.spring.model.Person;
  4. public interface PersonDAO {
  5. public void addPerson(Person p);
  6. public void updatePerson(Person p);
  7. public List<Person> listPersons();
  8. public Person getPersonById(int id);
  9. public void removePerson(int id);
  10. }

Hibernate specific DAO implementation looks like below.

PersonDAOImpl.java

  1. package com.journaldev.spring.dao;
  2. import java.util.List;
  3. import org.hibernate.Session;
  4. import org.hibernate.SessionFactory;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.stereotype.Repository;
  8. import com.journaldev.spring.model.Person;
  9. @Repository
  10. public class PersonDAOImpl implements PersonDAO {
  11. private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
  12. private SessionFactory sessionFactory;
  13. public void setSessionFactory(SessionFactory sf){
  14. this.sessionFactory = sf;
  15. }
  16. @Override
  17. public void addPerson(Person p) {
  18. Session session = this.sessionFactory.getCurrentSession();
  19. session.persist(p);
  20. logger.info("Person saved successfully, Person Details="+p);
  21. }
  22. @Override
  23. public void updatePerson(Person p) {
  24. Session session = this.sessionFactory.getCurrentSession();
  25. session.update(p);
  26. logger.info("Person updated successfully, Person Details="+p);
  27. }
  28. @SuppressWarnings("unchecked")
  29. @Override
  30. public List<Person> listPersons() {
  31. Session session = this.sessionFactory.getCurrentSession();
  32. List<Person> personsList = session.createQuery("from Person").list();
  33. for(Person p : personsList){
  34. logger.info("Person List::"+p);
  35. }
  36. return personsList;
  37. }
  38. @Override
  39. public Person getPersonById(int id) {
  40. Session session = this.sessionFactory.getCurrentSession();
  41. Person p = (Person) session.load(Person.class, new Integer(id));
  42. logger.info("Person loaded successfully, Person details="+p);
  43. return p;
  44. }
  45. @Override
  46. public void removePerson(int id) {
  47. Session session = this.sessionFactory.getCurrentSession();
  48. Person p = (Person) session.load(Person.class, new Integer(id));
  49. if(null != p){
  50. session.delete(p);
  51. }
  52. logger.info("Person deleted successfully, person details="+p);
  53. }
  54. }

Notice that I am not using Hibernate Transaction, that is because it will be taken care by Spring framework.

Spring Service Classes

Here are our service classes that are using Hibernate DAO classes to work with Person objects.

PersonService.java

  1. package com.journaldev.spring.service;
  2. import java.util.List;
  3. import com.journaldev.spring.model.Person;
  4. public interface PersonService {
  5. public void addPerson(Person p);
  6. public void updatePerson(Person p);
  7. public List<Person> listPersons();
  8. public Person getPersonById(int id);
  9. public void removePerson(int id);
  10. }

PersonServiceImpl.java

  1. package com.journaldev.spring.service;
  2. import java.util.List;
  3. import org.springframework.stereotype.Service;
  4. import org.springframework.transaction.annotation.Transactional;
  5. import com.journaldev.spring.dao.PersonDAO;
  6. import com.journaldev.spring.model.Person;
  7. @Service
  8. public class PersonServiceImpl implements PersonService {
  9. private PersonDAO personDAO;
  10. public void setPersonDAO(PersonDAO personDAO) {
  11. this.personDAO = personDAO;
  12. }
  13. @Override
  14. @Transactional
  15. public void addPerson(Person p) {
  16. this.personDAO.addPerson(p);
  17. }
  18. @Override
  19. @Transactional
  20. public void updatePerson(Person p) {
  21. this.personDAO.updatePerson(p);
  22. }
  23. @Override
  24. @Transactional
  25. public List<Person> listPersons() {
  26. return this.personDAO.listPersons();
  27. }
  28. @Override
  29. @Transactional
  30. public Person getPersonById(int id) {
  31. return this.personDAO.getPersonById(id);
  32. }
  33. @Override
  34. @Transactional
  35. public void removePerson(int id) {
  36. this.personDAO.removePerson(id);
  37. }
  38. }

Notice that spring declarative(声明) transaction management(事物管理) is applied by using @Transactional annotation.

Spring Controller Class

Our DAO and Service classes are ready, it’s time to write our controller class that will take care of client(客户端) requests and use service classes to perform(执行) database specific operations (特殊操作)and then return the view pages.

PersonController.java

  1. package com.journaldev.spring;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.beans.factory.annotation.Qualifier;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.Model;
  6. import org.springframework.web.bind.annotation.ModelAttribute;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import com.journaldev.spring.model.Person;
  11. import com.journaldev.spring.service.PersonService;
  12. @Controller
  13. public class PersonController {
  14. private PersonService personService;
  15. @Autowired(required=true)
  16. @Qualifier(value="personService")
  17. public void setPersonService(PersonService ps){
  18. this.personService = ps;
  19. }
  20. @RequestMapping(value = "/persons", method = RequestMethod.GET)
  21. public String listPersons(Model model) {
  22. model.addAttribute("person", new Person());
  23. model.addAttribute("listPersons", this.personService.listPersons());
  24. return "person";
  25. }
  26. //For add and update person both
  27. @RequestMapping(value= "/person/add", method = RequestMethod.POST)
  28. public String addPerson(@ModelAttribute("person") Person p){
  29. if(p.getId() == 0){
  30. //new person, add it
  31. this.personService.addPerson(p);
  32. }else{
  33. //existing person, call update
  34. this.personService.updatePerson(p);
  35. }
  36. return "redirect:/persons";
  37. }
  38. @RequestMapping("/remove/{id}")
  39. public String removePerson(@PathVariable("id") int id){
  40. this.personService.removePerson(id);
  41. return "redirect:/persons";
  42. }
  43. @RequestMapping("/edit/{id}")
  44. public String editPerson(@PathVariable("id") int id, Model model){
  45. model.addAttribute("person", this.personService.getPersonById(id));
  46. model.addAttribute("listPersons", this.personService.listPersons());
  47. return "person";
  48. }
  49. }

Notice that I am using @Controller annotation, so that Spring framework will treat it as a Controller class to handle(处理) client requests. Also I am using @Autowired and @Qualifier annotations for injecting PersonService(使用自动注入注解注入service), we could have done it in the spring context xml file too.

Recommended Read: Spring Bean Autowiring

Spring Bean Configuration

Our services are ready, all we need is to wire them through spring bean configurations. Our root-context.xml file is empty, so we will look only into servlet-context.xml file.

servlet-context.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans:beans xmlns="http://www.springframework.org/schema/mvc"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
  4. xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
  6. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  8. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
  9. <!-- DispatcherServlet Context: defines this servlet's request-processing
  10. infrastructure -->
  11. <!-- Enables the Spring MVC @Controller programming model -->
  12. <annotation-driven />
  13. <!-- Handles HTTP GET requests for /resources/** by efficiently serving
  14. up static resources in the ${webappRoot}/resources directory -->
  15. <resources mapping="/resources/**" location="/resources/" />
  16. <!-- Resolves views selected for rendering by @Controllers to .jsp resources
  17. in the /WEB-INF/views directory -->
  18. <beans:bean
  19. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  20. <beans:property name="prefix" value="/WEB-INF/views/" />
  21. <beans:property name="suffix" value=".jsp" />
  22. </beans:bean>
  23. <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  24. destroy-method="close">
  25. <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
  26. <beans:property name="url"
  27. value="jdbc:mysql://localhost:3306/TestDB" />
  28. <beans:property name="username" value="pankaj" />
  29. <beans:property name="password" value="pankaj123" />
  30. </beans:bean>
  31. <!-- Hibernate 4 SessionFactory Bean definition -->
  32. <beans:bean id="hibernate4AnnotatedSessionFactory"
  33. class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  34. <beans:property name="dataSource" ref="dataSource" />
  35. <beans:property name="annotatedClasses">
  36. <beans:list>
  37. <beans:value>com.journaldev.spring.model.Person</beans:value>
  38. </beans:list>
  39. </beans:property>
  40. <beans:property name="hibernateProperties">
  41. <beans:props>
  42. <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
  43. </beans:prop>
  44. <beans:prop key="hibernate.show_sql">true</beans:prop>
  45. </beans:props>
  46. </beans:property>
  47. </beans:bean>
  48. <beans:bean id="personDAO" class="com.journaldev.spring.dao.PersonDAOImpl">
  49. <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
  50. </beans:bean>
  51. <beans:bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
  52. <beans:property name="personDAO" ref="personDAO"></beans:property>
  53. </beans:bean>
  54. <context:component-scan base-package="com.journaldev.spring" />
  55. <tx:annotation-driven transaction-manager="transactionManager"/>
  56. <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  57. <beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
  58. </beans:bean>
  59. </beans:beans>

dataSource bean is defined for org.apache.commons.dbcp.BasicDataSource class for basic connection pooling.

org.springframework.orm.hibernate4.LocalSessionFactoryBean bean is used for Hibernate 4 SessionFactory. For Hibernate 3, you will find similar classes as org.springframework.orm.hibernate3.LocalSessionFactoryBean and org.springframework.orm.hibernate3.AnnotationSessionFactoryBean.

One important point is that when we are depending on Spring framework for Hibernate Session management, we should not define hibernate.current_session_context_class property, otherwise you will get a lot of session transaction related issues.

personDAO and personService beans are self understood.

transactionManager bean definition for org.springframework.orm.hibernate4.HibernateTransactionManager is required for Spring ORM to support hibernate session transaction management. For Hibernate 3, you will find similar class as org.springframework.orm.hibernate3.HibernateTransactionManager. Spring uses AOP for transaction management, you can now relate it with @Transactional annotation.

Recommended Read: Spring AOP and Spring Transaction Management

View Page

Our last part of application is the view page, notice the attributes added to Model in Controller handler methods, we will use them to create our view page. We will also use JSTL tags, spring core and spring form tags.

person.jsp

  1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  2. <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
  3. <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
  4. <%@ page session="false" %>
  5. <html>
  6. <head>
  7. <title>Person Page</title>
  8. <style type="text/css">
  9. .tg {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
  10. .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
  11. .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
  12. .tg .tg-4eph{background-color:#f9f9f9}
  13. </style>
  14. </head>
  15. <body>
  16. <h1>
  17. Add a Person
  18. </h1>
  19. <c:url var="addAction" value="/person/add" ></c:url>
  20. <form:form action="${addAction}" commandName="person">
  21. <table>
  22. <c:if test="${!empty person.name}">
  23. <tr>
  24. <td>
  25. <form:label path="id">
  26. <spring:message text="ID"/>
  27. </form:label>
  28. </td>
  29. <td>
  30. <form:input path="id" readonly="true" size="8" disabled="true" />
  31. <form:hidden path="id" />
  32. </td>
  33. </tr>
  34. </c:if>
  35. <tr>
  36. <td>
  37. <form:label path="name">
  38. <spring:message text="Name"/>
  39. </form:label>
  40. </td>
  41. <td>
  42. <form:input path="name" />
  43. </td>
  44. </tr>
  45. <tr>
  46. <td>
  47. <form:label path="country">
  48. <spring:message text="Country"/>
  49. </form:label>
  50. </td>
  51. <td>
  52. <form:input path="country" />
  53. </td>
  54. </tr>
  55. <tr>
  56. <td colspan="2">
  57. <c:if test="${!empty person.name}">
  58. <input type="submit"
  59. value="<spring:message text="Edit Person"/>" />
  60. </c:if>
  61. <c:if test="${empty person.name}">
  62. <input type="submit"
  63. value="<spring:message text="Add Person"/>" />
  64. </c:if>
  65. </td>
  66. </tr>
  67. </table>
  68. </form:form>
  69. <br>
  70. <h3>Persons List</h3>
  71. <c:if test="${!empty listPersons}">
  72. <table class="tg">
  73. <tr>
  74. <th width="80">Person ID</th>
  75. <th width="120">Person Name</th>
  76. <th width="120">Person Country</th>
  77. <th width="60">Edit</th>
  78. <th width="60">Delete</th>
  79. </tr>
  80. <c:forEach items="${listPersons}" var="person">
  81. <tr>
  82. <td>${person.id}</td>
  83. <td>${person.name}</td>
  84. <td>${person.country}</td>
  85. <td><a href="<c:url value='/edit/${person.id}' />" >Edit</a></td>
  86. <td><a href="<c:url value='/remove/${person.id}' />" >Delete</a></td>
  87. </tr>
  88. </c:forEach>
  89. </table>
  90. </c:if>
  91. </body>
  92. </html>

项目源码:链接:http://pan.baidu.com/s/1cC2WLw 密码:f7mm

Spring MVC Hibernate MySQL Integration(集成) CRUD Example Tutorial【摘】的更多相关文章

  1. Spring + Spring MVC + Hibernate项目开发集成(注解)

    在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护.于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下. ...

  2. Spring + Spring MVC + Hibernate

    Spring + Spring MVC + Hibernate项目开发集成(注解) Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏 在自 ...

  3. EasyUI + Spring MVC + hibernate实现增删改查导入导出

    (这是一个故事--) 前言 作为一个JAVA开发工程师,我觉得最基本是需要懂前端.后台以及数据库. 练习的内容很基础,包括:基本增删改查.模糊查询.分页查询.树菜单.上传下载.tab页 主管发我一个已 ...

  4. Java 本地开发环境搭建(框架采用 Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6)

    项目搭建采用技术栈为:Spring+Spring MVC+Hibernate+Jsp+Gradle+tomcat+mysql5.6 搭建环境文档目录结构说明: 使用Intellj Idea 搭建项目过 ...

  5. Spring MVC第一课:用IDEA构建一个基于Spring MVC, Hibernate, My SQL的Maven项目

    作为一个Spring MVC新手最基本的功夫就是学会如何使用开发工具创建一个完整的Spring MVC项目,本文站在一个新手的角度讲述如何一步一步创建一个基于Spring MVC, Hibernate ...

  6. Spring+Spring MVC+Hibernate增查(使用注解)

    使用Spring+Spring MVC+Hibernate做增删改查开发效率真的很高.使用Hibernate简化了JDBC连接数据库的的重复性代码.下面根据自己做的一个简单的增加和查询,把一些难点分析 ...

  7. Spring+Spring MVC+Hibernate环境搭配

    Spring+Spring MVC+Hibernate简称"SSH".Spring容器是Spring的核心,该 容器负责管理spring中的java组件.Spring的核心机制:依 ...

  8. IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践

    原文:IntelliJ IDEA:Getting Started with Spring MVC, Hibernate and JSON实践 最近把编辑器换成IntelliJ IDEA,主要是Ecli ...

  9. IntelliJIDEA Getting+Started+with+Spring+MVC,+Hibernate+and+JSON

    https://confluence.jetbrains.com/display/IntelliJIDEA/Getting+Started+with+Spring+MVC,+Hibernate+and ...

随机推荐

  1. Sql 中Collate用法

    今天查询sqlite的时候需要不区分大小写,查了下文档,需要使用collate nocase.顺便学习下collate的用法. collate在sql中是用来定义排序规则的.排序规则其实就是当比较两个 ...

  2. org.springframework.beans.factory.config.MethodInvokingFactoryBean的使用

    它有两种用法:一个是调用类的静态方法,一个是调用已在IOC容器中的bean的方法.调用结果也分两种,一种是有返回,那么也会作为bean注册到IOC容器中,另一种是没有返回值,那么实际上就是为了在启动时 ...

  3. delphi 2010安装unidac

    UniDAC是一个功能强大的非可视化跨数据库的数据访问组件,可用于Delphi,Delphi for .NET,C++Builder,and Lazarus (Free Pascal).它提供了对流行 ...

  4. WM_COMMAND 和 WM_NOTIFY 的区别

    当我们按下一个菜单选项,或者一个控件需要通知父窗口一个事件发生(如鼠标单击.双击等),或者快捷键被按下时,Windows将会发送一个 WM_COMMAND 消息给父窗口.那么 WM_COMMAND 消 ...

  5. DHCP(六)

    DHCP报文: DHCP共有八种报文,分别为DHCP Discover.DHCP Offer.DHCP Request.DHCP ACK.DHCP NAK.DHCP Release.DHCP Decl ...

  6. java代码,输入n多个数,求其平均值,虽有重复,但是第二次,我就乱写了

    总结:对象调用方法,与在main 里直接输出没什么大的区别,少用方法, 乱搞++++ package com.c2; import java.util.Scanner; public class DD ...

  7. WebSocket :Nginx+WebSocket内部路由策略推送服务器的实现(附可生产环境应用代码)

    1.项目背景 前几天写了一篇WebSocket推送的博客:WebSocket :用WebSocket实现推送你必须考虑的几个问题 支持的连接数大概几千个,具体数量依赖于tomcat能并发的线程数,但很 ...

  8. Tomcat下WebSocket最大连接数测试

    WebSocket现在很常用,想要测试tomcat的最大连接数,今天试了一个可行的办法和配置(之前是用全公司的设备一起来测试的,真机环境的测试收到网络的影响很大,其实真实环境应用中,网络才是webso ...

  9. git的分布式和集中式

    当然,Git的优势不单是不必联网这么简单,后面我们还会看到Git极其强大的分支管理,把SVN等远远抛在了后面.

  10. JavaScript笔记——事件

    事件一般是用于浏览器和用户操作进行交互.最早是 IE 和 Netscape Navigator 中出现, 作为分担服务器端运算负载的一种手段.直到几乎所有的浏览器都支持事件处理.而 DOM2 级规范开 ...