采用Spring MVC ,Hibernate , My SQL 进行整合示例,以学生信息的添加,删除,修改,查看为基础,结合spring mvc 和 hibernate 对My SQL DB 的操作。
使用技术:
1.Spring 4.3.3.RELEASE
2.Hibernate 4.3.8
3.Maven 3
4.JDK 1.7
5.Eclipse 4.4
6.Boostrap 3
7.My SQL5

一,项目结构

二,Maven Pom.xml 配置

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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<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.devnp</groupId>
<artifactId>SpringMVC4Hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC4Hibernate Maven Webapp</name>

<properties>
<project.name>SpringMVC4Hibernate</project.name>
<jdk.version>1.7</jdk.version>
<spring.version>4.3.3.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<jackson.version>2.7.5</jackson.version>
<servletapi.version>2.5</servletapi.version>
<sl4j.version>1.7.9</sl4j.version>

<jdbc.groupId>mysql</jdbc.groupId>
<jdbc.artifactId>mysql-connector-java</jdbc.artifactId>
<jdbc.version>5.1.40</jdbc.version>
<jdbc.driverClassName>com.mysql.jdbc.Driver</jdbc.driverClassName>
<hibernate.dialect>org.hibernate.dialect.MySQLDialect</hibernate.dialect>
</properties>


<url>http://maven.apache.org</url>

<dependencies>
<!-- spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>${hibernate.version}</version>
</dependency>

<!-- json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>

<!-- JDBC dependency START -->
<dependency>
<groupId>${jdbc.groupId}</groupId>
<artifactId>${jdbc.artifactId}</artifactId>
<version>${jdbc.version}</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servletapi.version}</version>
<scope>provided</scope>
</dependency>

<!-- log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${sl4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${sl4j.version}</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>

</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<encoding>UTF-8</encoding>
<excludes>
<exclude>**/test/*.java</exclude>
</excludes>
</configuration>
</plugin>
<!-- embedded Jetty server, for testing -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.11.v20150529</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/${project.name}</contextPath>
</webApp>
<httpConnector>
<port>9999</port>
</httpConnector>
</configuration>
</plugin>
<!-- configure Eclipse workspace -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
<wtpversion>2.0</wtpversion>
<wtpContextName>${project.name}</wtpContextName>
</configuration>
</plugin>

</plugins>
<finalName>${project.name}</finalName>
</build>
</project>

三,Spring MVC xml 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

<context:component-scan base-package="com.devnp" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

<mvc:annotation-driven />

<import resource="sys-config.xml"/>
</beans>

四,系统 xml 配置

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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<context:property-placeholder location="classpath:jdbc.properties" />

<!-- Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="devnpDS" />
<property name="hibernateProperties" ref="sampleHibernateProperties" />
<property name="packagesToScan">
<list>
<value>com.devnp.to</value>
</list>
</property>
</bean>

<!-- Hibernate Properties -->
<bean id="sampleHibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<!-- <prop key="hibernate.query.substitutions">true 'T', false 'F'</prop> -->
<prop key="hibernate.jdbc.batch_size">30</prop>

<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>

<!-- For Envers Configurations, to specify here -->
<prop key="org.hibernate.envers.auditTableSuffix">_AUD</prop>
<prop key="org.hibernate.envers.revisionTypeFieldName">REV_TYPE</prop>
<prop key="org.hibernate.envers.doNotAuditOptimisticLockingField">false</prop>
</props>
</property>
</bean>

<!-- TransactionManager -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<constructor-arg name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- For Transparent Exception Translation -->
<bean id="persistenceExceptionInterceptor" class="org.springframework.dao.support.PersistenceExceptionTranslationInterceptor" />

<aop:config>
<aop:advisor advice-ref="persistenceExceptionInterceptor" pointcut="execution(* *..dao.*DAO(..))" />
</aop:config>

<!-- txAdvice -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="*" propagation="REQUIRED" />

<tx:method name="save" propagation="REQUIRED" />

<!-- <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="*" read-only="true"/> -->

</tx:attributes>
</tx:advice>

<!-- uses JDK Dynamic Proxy instead of CGLIB Proxy, default proxy-target-class="false" -->
<aop:config>
<aop:pointcut id="interceptorPointCuts" expression="execution(* *..service.*Service+.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
</aop:config>


<!-- Datasource START -->
<jee:jndi-lookup id="devnpDS" jndi-name="jdbc/devnpDS" lookup-on-startup="false" proxy-interface="javax.sql.DataSource" cache="true" resource-ref="true" />
<!-- Datasource END -->
</beans>

五,web.xml 配置

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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

六,Entity代码

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
package com.devnp.to;

import java.util.Date;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.springframework.format.annotation.DateTimeFormat;

@javax.persistence.Entity
@org.hibernate.envers.Audited
@Table(name = "STUDENT")
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "ID")
private Integer id ;

@Column(name = "S_NAME", length=30)
private String sName ;

@Column(name = "S_SEX", length=1)
private String sSex ;

@Column(name = "S_AGE")
private Integer sAge ;

@DateTimeFormat(pattern="dd/MM/yyyy")
@Column(name = "S_BIRTH")
private Date sBirth ;

public Student() {

}

public Integer getId() {
return id;
}

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

public String getsName() {
return sName;
}

public void setsName(String sName) {
this.sName = sName;
}

public String getsSex() {
return sSex;
}

public void setsSex(String sSex) {
this.sSex = sSex;
}

public Integer getsAge() {
return sAge;
}

public void setsAge(Integer sAge) {
this.sAge = sAge;
}

public Date getsBirth() {
return sBirth;
}

public void setsBirth(Date sBirth) {
this.sBirth = sBirth;
}

}

七,web controller 代码

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
package com.devnp.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.devnp.service.StudentService;
import com.devnp.to.Student;

@Controller
public class StudentController {

@Autowired
private StudentService studentService ;

@RequestMapping(value = "/")
public String index(Model model){

List<Student> students = studentService.findAll();

model.addAttribute("students", students);

return "index";
}

@RequestMapping("/initAddStudent")
public ModelAndView initAddStudent(){

return new ModelAndView("edit", "student", new Student());
}

@RequestMapping(value="/delStudent/{id}")
public String delStudent(@PathVariable(value="id") Integer id){

studentService.delete(id);

return "forward:/" ;
}

@RequestMapping(value="/initEditStudent/{id}")
public ModelAndView initEditStudent(@PathVariable(value="id") Integer id){

Student student = studentService.findById(id);

return new ModelAndView("edit", "student", student);
}

@RequestMapping("/editStudent")
public String editStudent(Student student){

studentService.update(student);

return "forward:/" ;
}

@RequestMapping("/addStudent")
public String addStudent(Student student){

studentService.save(student);

return "forward:/" ;
}
}

八,service 代码

1.Service 接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.devnp.service;

import java.util.List;

import com.devnp.to.Student;

public interface StudentService {

public void save(Student student);

public void update(Student student);

public void delete(Integer id);

public Student findById(Integer id);

public List<Student> findAll();
}

2.Service 实现类

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
package com.devnp.service;

import java.util.List;

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

import com.devnp.dao.StudentDAO;
import com.devnp.to.Student;

@Service("studentService")
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentDAO studentDAO ;

public void save(Student student) {
// TODO Auto-generated method stub
studentDAO.save(student);
}

public void update(Student student) {
// TODO Auto-generated method stub
studentDAO.update(student);
}

public void delete(Integer id) {
// TODO Auto-generated method stub
studentDAO.delete(id);
}

public Student findById(Integer id) {
// TODO Auto-generated method stub
return studentDAO.findById(id);
}

public List<Student> findAll() {
// TODO Auto-generated method stub
return studentDAO.findAll();
}

}

九,Dao 代码

1.Dao 接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.devnp.dao;

import java.util.List;

import com.devnp.to.Student;

public interface StudentDAO {

public void save(Student student);

public void update(Student student);

public void delete(Integer id);

public Student findById(Integer id);

public List<Student> findAll();
}

2.Dao 实现类

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.devnp.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.devnp.to.Student;

@Repository("studentDao")
public class StudentDAOImpl implements StudentDAO {

@Autowired
private HibernateTemplate hibernateTemplate ;


public StudentDAOImpl(){

}

public void save(Student student) {
// TODO Auto-generated method stub
hibernateTemplate.save(student);
}

public void update(Student student) {
// TODO Auto-generated method stub
hibernateTemplate.update(student);
}

public void delete(Integer id) {
// TODO Auto-generated method stub
Student student = new Student();
student.setId(id);

hibernateTemplate.delete(student);
}

public Student findById(Integer id) {
// TODO Auto-generated method stub
return hibernateTemplate.get(Student.class, id);
}

@SuppressWarnings("unchecked")
public List<Student> findAll() {
// TODO Auto-generated method stub
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);

return (List<Student>) hibernateTemplate.findByCriteria(detachedCriteria, 0, 100);
}

}

十,测试

1.访问

2.点击添加按钮

3.输入信息,点击添加(多次添加之后)

4.点击编辑

5.修改信息

6.点击删除

十一,代码下载

SpringMVC4Hibernate.zip