Spring + Spring MVC + Hibernate项目开发集成(注解)
Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏
在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护。于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下。在网上也查询了很多使用注解来搭建开发框架的文章,但是有一个问题就是,使用更新的软件版本会出错。这里我将使用最新的Spring,Hibernate来进行框架的搭建,经过测试,顺利运行。分享旨在与大家一起分享学习,共同进步,有不足之处,望不吝赐教,谢谢!
本项目使用maven构建,采用Spring + Spring MVC + Hibernate + MySQL进行搭建,下面简要说明本项目所使用软件版本:
maven:3.2.3
hibernate:4.3.9.Final
spring:4.1.6.RELEASE
mysql:5.1.35
接下来我看一下项目的整体结构:
下面我们开始框架的搭建之旅吧。
一,配置文件
1,首先配置pom.xml,获得项目所需要的jar文件。
<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>cn</groupId> <artifactId>mylife</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>mylife Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 设置使用框架的版本 --> <properties> <hibernate-version>4.3.9.Final</hibernate-version> <spring-version>4.1.6.RELEASE</spring-version> <mysql-driver-version>5.1.35</mysql-driver-version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- servlet api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate-version}</version> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc-portlet</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <version>${spring-version}</version> </dependency> <!-- MySQL驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-driver-version}</version> </dependency> <!-- dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies> <build> <finalName>mylife</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
2,配置Spring MVC,在calsspath路径下创建一个spring-mvc.xml文件,具体配置如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:cache="http://www.springframework.org/schema/cache" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:jdbc="http://www.springframework.org/schema/jdbc" 8 xmlns:jee="http://www.springframework.org/schema/jee" 9 xmlns:jms="http://www.springframework.org/schema/jms" 10 xmlns:lang="http://www.springframework.org/schema/lang" 11 xmlns:mvc="http://www.springframework.org/schema/mvc" 12 xmlns:oxm="http://www.springframework.org/schema/oxm" 13 xmlns:task="http://www.springframework.org/schema/task" 14 xmlns:tx="http://www.springframework.org/schema/tx" 15 xmlns:util="http://www.springframework.org/schema/util" 16 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 17 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 18 http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd 19 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 20 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd 21 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd 22 http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd 23 http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd 24 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 25 http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd 26 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd 27 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 28 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> 29 <!-- 扫描controller组件 --> 30 <context:component-scan base-package="cn.mylife.controller"/> 31 <!-- 配置视图解析器 --> 32 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 33 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> 34 <property name="prefix" value="/WEB-INF/" /> 35 <property name="suffix" value=".jsp" /> 36 </bean> 37 <!-- 启动springMVC注解 --> 38 <mvc:annotation-driven/> 39 40 </beans>
3,配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>mylife</display-name> <!-- 启动服务时加载的文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <context-param> <!-- 日志配置文件路径 --> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <!-- 日志页面的刷新间隔 --> <param-name>log4jRefreshInterval</param-name> <param-value>6000</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</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> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <error-page> <error-code>404</error-code> <location>/404.html</location> </error-page> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
4,配置Spring,在classpath路径下新建applicationContext.xml文件,配置如下:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd" default-autowire="byName" default-lazy-init="true"> <context:component-scan base-package="cn.mylife"/> <context:property-placeholder location="classpath:hibernate.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!-- 这一个必须配置,否则会出现no session 的错误 --> <!-- <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop> --> </props> </property> <!-- 自动扫描制定位置下的实体进行映射 --> <property name="packagesToScan" value="cn.mylife.entity"/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
二,代码实现
1,创建entity实体类:cn.mylife.entity.User
package cn.mylife.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * 用户User实体类 * @author Xiongyan * @date 2015年5月6日 上午10:24:24 * @version 0.0.1 */ @SuppressWarnings("serial") @Entity @Table(name="tb_user") public class User implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(name="user_name", length=50, nullable=false) private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2,实现dao层基类:cn.mylife.dao.BaseDao<T>
package cn.mylife.dao; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; /** * dao层基类,实现增,删,改,查等常用功能。 * * @author Xiongyan * @date 2015年5月6日 下午5:24:08 * @version 0.0.1 * @param <T> */ @Repository public class BaseDao<T> { @Resource private SessionFactory sessionFactory; /** * 保存数据 * * @author Xiongyan * @date 2015年5月6日 下午5:24:54 * @throws * @return void 返回类型 */ public void save(T t) { sessionFactory.getCurrentSession().save(t); } /** * 删除数据 * * @author Xiongyan * @date 2015年5月6日 下午5:26:41 * @throws * @return void 返回类型 */ public void delete(Serializable id, Class<T> clazz) { T t = get(id, clazz); if (t != null) sessionFactory.getCurrentSession().delete(t); else new RuntimeException("你要删除的数据不存在").printStackTrace(); ; } /** * 更新数据 * * @author Xiongyan * @date 2015年5月6日 下午5:29:13 * @throws * @return void 返回类型 */ public void update(T t) { sessionFactory.getCurrentSession().update(t); } /** * 根据ID查找数据 * * @author Xiongyan * @date 2015年5月6日 下午5:29:46 * @throws * @return T 返回类型 */ @SuppressWarnings("unchecked") public T get(Serializable id, Class<T> clazz) { return (T) sessionFactory.getCurrentSession().get(clazz, id); } /** * 查找所有数据 * * @author Xiongyan * @date 2015年5月6日 下午5:30:16 * @throws * @return List<T> 返回类型 */ @SuppressWarnings("unchecked") public List<T> getAll(Class<T> clazz) { return sessionFactory.getCurrentSession().createQuery(clazz.toString()).list(); } }
3,service层代码的实现
package cn.mylife.service.user; import java.io.Serializable; import java.util.List; import javax.transaction.Transactional; /** * Service层基类,定义通用的增,删,改,查功能接口。 * * @author Xiongyan * @date 2015年5月6日 下午5:41:57 * @version 0.0.1 * @param <T> */ public interface BaseService<T> { /** * 保存数据 * * @author Xiongyan * @date 2015年5月6日 下午5:42:42 * @throws * @return void 返回类型 */ @Transactional public void save(T t); /** * 删除数据 * * @author Xiongyan * @date 2015年5月6日 下午5:43:08 * @throws * @return void 返回类型 */ @Transactional public void delete(Serializable id); /** * 更新数据 * * @author Xiongyan * @date 2015年5月6日 下午5:43:19 * @throws * @return void 返回类型 */ @Transactional public void update(T t); /** * 根据ID获取数据 * * @author Xiongyan * @date 2015年5月6日 下午5:43:30 * @throws * @return T 返回类型 */ public T get(Serializable id); /** * 获取所有的数据 * * @author Xiongyan * @date 2015年5月6日 下午5:43:52 * @throws * @return List<T> 返回类型 */ public List<T> getAll(); }
package cn.mylife.service.user.impl; import java.io.Serializable; import java.util.List; import javax.annotation.Resource; import cn.mylife.dao.BaseDao; import cn.mylife.service.user.BaseService; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * Service层基类实现类。该类是一个抽象类。 * @author Xiongyan * @date 2015年5月6日 下午6:59:53 * @version 0.0.1 * @param <T> */ public abstract class BaseServiceImpl<T> implements BaseService<T> { @Resource private BaseDao<T> baseDao; private Class<T> clazz; @SuppressWarnings({ "unchecked", "rawtypes" }) public BaseServiceImpl() { // 子类 Class cla = getClass(); // 通过子类获取到父类 // 泛型参数 Type type = cla.getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; clazz = (Class<T>) pType.getActualTypeArguments()[0]; } } /* * 保存数据 * @author Xiongyan * @date 2015年5月6日 下午6:55:23 * (non-Javadoc) * @throws * @see cn.mylife.service.user.BaseService#save(java.lang.Object) */ @Override public void save(T t) { baseDao.save(t); } /* * 根据ID删除数据 * @author Xiongyan * @date 2015年5月6日 下午6:56:01 * (non-Javadoc) * @throws * @see cn.mylife.service.user.BaseService#delete(java.io.Serializable) */ @Override public void delete(Serializable id) { baseDao.delete(id, clazz); } /* * 更新数据 * @author Xiongyan * @date 2015年5月6日 下午6:56:51 * (non-Javadoc) * @throws * @see cn.mylife.service.user.BaseService#update(java.lang.Object) */ @Override public void update(T t) { baseDao.update(t); } /* * 根据ID获得数据 * @author Xiongyan * @date 2015年5月6日 下午6:57:54 * (non-Javadoc) * @throws * @see cn.mylife.service.user.BaseService#get(java.io.Serializable) */ @Override public T get(Serializable id) { return baseDao.get(id, clazz); } /* * 获取所有的数据 * @author Xiongyan * @date 2015年5月6日 下午6:58:34 * (non-Javadoc) * @throws * @see cn.mylife.service.user.BaseService#getAll() */ @Override public List<T> getAll() { return baseDao.getAll(clazz); } }
package cn.mylife.service.user; import cn.mylife.entity.User; public interface UserService extends BaseService<User>{ }
package cn.mylife.service.user.impl; import org.springframework.stereotype.Service; import cn.mylife.entity.User; import cn.mylife.service.user.UserService; @Service public class UserServiceImpl extends BaseServiceImpl<User> implements UserService{ }
4,controller层代码的实现
package cn.mylife.controller; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user") @Scope("prototype") public class UserController { @RequestMapping(value = "/save") public ModelAndView saveUser() { ModelAndView view = new ModelAndView("/jsps/testPage"); System.out.println("-- 访问成功 --"); return view; } }
5,编写JSP页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试页面</title> </head> <body> 这只是一个测试页面。 </body> </html>
6,编写Spring测试代码:cn.mylife.junit.SpringJunit4.java
package cn.mylife.junit; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cn.mylife.entity.User; import cn.mylife.service.user.UserService; @RunWith(SpringJUnit4ClassRunner.class) // 加载spring配置文件 @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) public class SpringJunit4 { @Resource private UserService userService; @Test public void testUser() throws Exception { User user = new User(); user.setName("中国人名共和国"); userService.save(user); } }
7,运行测试
我们的测试代码运行成功,下面我们看一下数据库
8,接下来我们测试一下Spring MVC。在浏览器中输入:http://localhost/mylife/user/save.do
至此,咱们的开发框架搭建完成,本文还有很多不足和需要完善的地方,望指出,谢谢!
标签: spring, spring mvc, hibernate, maven, 注解