Spring MVC + Spring Data + Hibernate + MySQL示例
在本教程中,我们将看到Spring MVC,Spring Data,Hibernate和MySQL Crud示例的集成。
Spring Data JPA提供CRUD API,因此我们不必编写锅炉板代码。
我们只需要创建存储库界面,Spring 将自动提供实现。
以下是使用Spring MVC,Spring Data,Hibernate和MySQL CRUD示例创建项目的步骤。
1)使用名为"springmvcspringdatahibernateExample"的Eclipse中的Maven创建动态Web项目
Maven依赖项
2)我们将使用Spring 4和Hibernate 4进行此项目。
pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.igi.theitroad</groupId>
<artifactId>SpringMVCHibernateCRUDExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVCHibernateCRUDExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.Hymanson.core</groupId>
<artifactId>Hymanson-databind</artifactId>
<version>2.4.1</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCHibernateCRUDExample</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.version>4.2.1.RELEASE</spring.version>
<security.version>4.0.3.RELEASE</security.version>
<jdk.version>1.7</jdk.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<org.aspectj-version>1.7.4</org.aspectj-version>
</properties>
</project>
Spring应用程序配置:
3)更改Web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationcontext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4)在/web-inf /文件夹中创建名为spring-servlet.xml的XML文件。
请更改上下文:组件扫描如果要使用不同的套装来搜索控制器。
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<annotation-driven
<context:component-scan base-package="org.igi.theitroad"
<resources mapping="/resources/**" location="/resources/"
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/"
<beans:property name="suffix" value=".jsp"
</beans:bean>
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="entityManagerFactory"
</beans:bean>
<jpa:repositories base-package="org.igi.theitroad.repository"
<beans:bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource"
<beans:property name="packagesToScan" value="org.igi.theitroad"
<beans:property name="jpaVendorAdapter">
<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans:property name="generateDdl" value="true"
</beans:bean>
</beans:property>
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver"
<beans:property name="url"
value="jdbc:mysql://localhost:3306/CountryData"
<beans:property name="username" value="root"
<beans:property name="password" value="igi123"
</beans:bean >
</beans:beans>
在Spring-servlet.xml中,我们已经完成了Hibernate和Spring数据配置。
DataSource Bean用于指定Java数据源。
我们需要提供驱动程序,URL,用户名和密码。
TransactionManager Bean用于配置Hibernate Transaction Manager。
在Web-Inf文件夹中创建ApplicationContext.xml,此文件用于Bean配置,因为我们使用Spring-servlet.xml for bean配置,我们将保留此文件。
<!--?xml version="1.0" encoding="UTF-8"?--> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> </beans:beans>
创建bean类
4)在org.igi.theitroad.Bean中创建Bean名称"country.java"。
package org.igi.theitroad.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;
/*
* This is our model class and it corresponds to Country table in database
*/
@Entity
@Table(name="COUNTRY")
public class Country{
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
@Column(name="countryName")
String countryName;
@Column(name="population")
long population;
public Country() {
super();
}
public Country(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
@entity用于制作持久性POJO类。
对于此Java类,我们将在数据库中具有相应的表。
@column用于将注释属性映射到表中的相应列。
所以在MySQL数据库中创建Country表,其中包含以下代码:
CREATE TABLE COUNTRY ( id int PRIMARY KEY NOT NULL AUTO_INCREMENT, countryName varchar(100) NOT NULL, population int NOT NULL ) ;
创建控制器
5)在包org.igi.theitroad.Controller中创建名为"countrycontroller.java"的控制器
package org.igi.theitroad.controller;
import java.util.List;
import org.igi.theitroad.model.Country;
import org.igi.theitroad.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class CountryController {
@Autowired
CountryService countryService;
@RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json")
public String getCountries(Model model) {
List listOfCountries = countryService.getAllCountries();
model.addAttribute("country", new Country());
model.addAttribute("listOfCountries", listOfCountries);
return "countryDetails";
}
@RequestMapping(value = "/getCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Country getCountryById(@PathVariable int id) {
return countryService.getCountry(id);
}
@RequestMapping(value = "/addCountry", method = RequestMethod.POST, headers = "Accept=application/json")
public String addCountry(@ModelAttribute("country") Country country) {
if(country.getId()==0)
{
countryService.addCountry(country);
}
else
{
countryService.updateCountry(country);
}
return "redirect:/getAllCountries";
}
@RequestMapping(value = "/updateCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public String updateCountry(@PathVariable("id") int id,Model model) {
model.addAttribute("country", this.countryService.getCountry(id));
model.addAttribute("listOfCountries", this.countryService.getAllCountries());
return "countryDetails";
}
@RequestMapping(value = "/deleteCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public String deleteCountry(@PathVariable("id") int id) {
countryService.deleteCountry(id);
return "redirect:/getAllCountries";
}
}
创建存储库界面
在package org.igi.theitroad.Repository中创建一个名为countryRepository .java的界面。
我们不必提供此接口的实现。
Spring自动提供常用方法的实现,例如Save,Delete,FindOne一旦扩展到CrudRepository接口。
package org.igi.theitroad.repository;
import org.igi.theitroad.model.Country;
import org.springframework.data.repository.CrudRepository;
public interface CountryRepository extends CrudRepository<Country,Integer> {
}
CrudRepository有两个通用参数。
国家:它是我们将在数据库中保存的类型的实体。
Integer:它是实体对象标识符的数据类型。
创建服务类
6)在包org.igi.theitroad.service中创建一个countropyservice.java .service是服务级别类。
它会调用DAO图层类。
package org.igi.theitroad.service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.igi.theitroad.model.Country;
import org.igi.theitroad.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("countryService")
public class CountryService {
@Autowired
CountryRepository countryRepository;
@Transactional
public List getAllCountries() {
List countries=new ArrayList();
Iterable countriesIterable=countryRepository.findAll();
Iterator countriesIterator=countriesIterable.iterator();
while(countriesIterator.hasNext())
{
countries.add(countriesIterator.next());
}
return countries;
}
@Transactional
public Country getCountry(int id) {
return countryRepository.findOne(id);
}
@Transactional
public void addCountry(Country country) {
countryRepository.save(country);
}
@Transactional
public void updateCountry(Country country) {
countryRepository.save(country);
}
@Transactional
public void deleteCountry(int id) {
countryRepository.delete(id);
}
}
@Service是专门的组件注释,用于在服务层创建bean。
创建视图
在Web-Inf/View /文件夹中创建名为countrydetails.jsp的视图。
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<style>
.blue-button{
background: #25A6E1;
filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
padding:3px 5px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:12px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:4px;
border:1px solid #1A87B9
}
table {
font-family: "Helvetica Neue", Helvetica, sans-serif;
width: 50%;
}
th {
background: SteelBlue;
color: white;
}
td,th{
border: 1px solid gray;
width: 25%;
text-align: left;
padding: 5px 10px;
}
</style>
</head>
<body>
<form:form method="post" modelAttribute="country" action="${pageContext.request.contextPath}/addCountry">
<table>
<tr>
<th colspan="2">Add Country</th>
</tr>
<tr>
<form:hidden path="id"
<td><form:label path="countryName">Country Name:</form:label></td>
<td><form:input path="countryName" size="30" maxlength="30"></form:input></td>
</tr>
<tr>
<td><form:label path="population">Population:</form:label></td>
<td><form:input path="population" size="30" maxlength="30"></form:input></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
class="blue-button" </td>
</tr>
</table>
</form:form>
</br>
<h3>Country List</h3>
<c:if test="${!empty listOfCountries}">
<table class="tg">
<tr>
<th width="80">Id</th>
<th width="120">Country Name</th>
<th width="120">Population</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${listOfCountries}" var="country">
<tr>
<td>{country.id}</td>
<td>${country.countryName}</td>
<td>${country.population}</td>
<td><a href="<c:url value='/updateCountry/${country.id}' " >Edit</a></td>
<td><a href="<c:url value='/deleteCountry/${country.id}' " >Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
8)是时候做Maven建造了。
右键单击项目 - >运行AS - > Maven Build
9)将目标作为清洁安装(下面给出),然后单击运行
运行应用程序
10)右键单击项目 - >在服务器上运行 - >运行
选择Apache Tomcat,然后单击"完成"
11)现在让我们以低于GetallCountries命中。
http://localhost:8080/springmvcspringdatahibernateexample/getallcountries我们将得到以下屏幕:
正如我们所看到的,我们没有将任何国家添加到列表中,因此它是空的。
让我们将命名的国家命名为Country List,然后单击"提交"。

