1. 说明: 采用maven3对springmvc3 + JPA2(Hibernate4实现) 整合
目录结构:
2. web.xml 配置
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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"> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:/applicationContext.xml </param-value> </context-param> <!-- Spring 刷新Introspector防止内存泄露 --> <listener> <listener-class> org.springframework.web.util.IntrospectorCleanupListener </listener-class> </listener> <!-- 配置Srping监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- SpringMVC核心分发器 --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-mvc.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> </web-app>
3. 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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd" default-lazy-init="true"> <!-- 加载properties文件 --> <context:property-placeholder location="classpath*:/config.properties" ignore-resource-not-found="true" ignore-unresolvable="true" /> <!-- 扫描工程目录下面所有带@Service @Resources等注解(除了@Controller) --> <context:component-scan base-package="com.ryan"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 配置DBCP数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/yde?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <!-- 配置JPA实体管理工厂 --> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- <property name="persistenceProvider" ref="persistenceProvider" />--> <property name="jpaVendorAdapter"> <!-- 用于设置JPA实现厂商的特定属性 --> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="generateDdl" value="true" /> </bean> </property> <property name="jpaDialect" ref="jpaDialect" /> <!-- 扫描实体类包 --> <property name="packagesToScan" value="com.ryan.entity"/> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- 用于指定持久化实现厂商类 --> <bean id="persistenceProvider" class="org.hibernate.ejb.HibernatePersistence" /> <!-- 用于指定一些高级特性 --> <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /> <!-- Jpa 事务配置 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <!-- 启动注解事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
4. applicationContext-mvc.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd" default-lazy-init="true"> <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射--> <mvc:annotation-driven /> <!-- 扫描com.ryan.controller包下面标有@Controller注解的控制器类 --> <context:component-scan base-package="com.ryan.controller" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 对模型视图名称的解析,在WEB-INF/jsp目录下找对应的jsp文件 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> </beans>
5. config.properties 数据库属性配置
#------------ JDBC ------------ jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/yde?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456
6. BaseDao接口
/** * @author yde * @date 2014-1-21 下午07:14:20 * @version V1.0 * @Description: DAO基础接口 */ package com.ryan.dao; import java.io.Serializable; import java.util.List; public interface BaseDao<T, ID extends Serializable> { //保存实体对象 void persist(T entity); //修改实体对象 T meger(T entity); //删除实体对象 void remove(T entity); //根据ID获取实体对象 T find(ID id); //获取实体对象集合--分页 List<T> findList(Integer start, Integer limit); }
7. BaseDaoImpl 实现类
/** * @author yde * @date 2014-1-21 下午07:24:39 * @version V1.0 * @Description: TODO */ package com.ryan.dao.impl; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.FlushModeType; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import org.springframework.util.Assert; import com.ryan.dao.BaseDao; public class BaseDaoImpl<T, ID extends Serializable> implements BaseDao<T, ID> { private Class<T> entityClass; //注入的是实体管理器 @PersistenceContext protected EntityManager entityManager; @SuppressWarnings("unchecked") public BaseDaoImpl() { Type type = getClass().getGenericSuperclass();//Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type //返回表示此类型实际类型参数的 Type 对象的数组。 Type[] parameterizedType = ((ParameterizedType)type).getActualTypeArguments(); entityClass = (Class<T>)parameterizedType[0]; } @Override public T find(ID id) { if (id != null) return entityManager.find(entityClass, id); return null; } @Override public List<T> findList(Integer first, Integer count) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass); criteriaQuery.select(criteriaQuery.from(entityClass)); TypedQuery<T> query = entityManager.createQuery(criteriaQuery).setFlushMode(FlushModeType.COMMIT); if (first != null) { query.setFirstResult(first); } if (count != null) { query.setMaxResults(count); } return query.getResultList(); } @Override public T meger(T entity) { return entityManager.merge(entity); } @Override public void persist(T entity) { Assert.notNull(entity); entityManager.persist(entity); } @Override public void remove(T entity) { if (entity != null) entityManager.remove(entity); } }
8. BaseService.java
/** * @author yde * @date 2014-1-21 下午07:40:43 * @version V1.0 * @Description: TODO */ package com.ryan.service; import java.io.Serializable; import java.util.List; public interface BaseService<T, ID extends Serializable> { //保存实体对象 void save(T entity); //更新实体对象 T update(T entity); //删除实体对象 void delete(ID id); void delete(ID... id); void delete(T entity); //获取实体对象 T find(ID id); //分页获取实体集合 List<T> findList(Integer start, Integer limit); //获取实体对象集合 List<T> findAll(); }
9. BaseServiceImpl 实现类
/** * @author yde * @date 2014-1-21 下午07:44:26 * @version V1.0 * @Description: TODO */ package com.ryan.service.impl; import java.io.Serializable; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.ryan.dao.BaseDao; import com.ryan.service.BaseService; @Transactional public class BaseServiceImpl<T, ID extends Serializable> implements BaseService<T, ID> { private BaseDao<T, ID> baseDao; public void setBaseDao(BaseDao<T, ID> baseDao) { this.baseDao = baseDao; } @Override public void delete(ID id) { baseDao.remove(find(id)); } @Override public void delete(ID... id) { // TODO Auto-generated method stub } @Override public void delete(T entity) { // TODO Auto-generated method stub } @Override public T find(ID id) { return baseDao.find(id); } @Override public List<T> findAll() { // TODO Auto-generated method stub return null; } @Transactional public void save(T entity) { baseDao.persist(entity); } @Override public T update(T entity) { return baseDao.meger(entity); } @Override public List<T> findList(Integer start, Integer limit) { return baseDao.findList(start, limit); } }
10. 实体类
/** * @author yde * @date 2014-1-21 下午07:07:58 * @version V1.0 * @Description: TODO */ package com.ryan.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "t_user") public class User { private Long id; private String username; private String password; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
11. UserDao.java
/** * @author yde * @date 2014-1-21 下午07:13:28 * @version V1.0 * @Description: TODO */ package com.ryan.dao; import com.ryan.entity.User; public interface UserDao extends BaseDao<User, Long>{ }
12. UserDaoImpl 实现类
/** * @author yde * @date 2014-1-21 下午07:13:45 * @version V1.0 * @Description: TODO */ package com.ryan.dao.impl; import org.springframework.stereotype.Repository; import com.ryan.dao.UserDao; import com.ryan.entity.User; @Repository("userDao") public class UserDaoImpl extends BaseDaoImpl<User, Long> implements UserDao { }
13. UserService.java
/** * @author yde * @date 2014-1-21 下午02:58:43 * @version V1.0 * @Description: TODO */ package com.ryan.service; import com.ryan.entity.User; public interface UserService extends BaseService<User, Long>{ User isExistByUsername(String username); }
14. UserServiceImpl 实现类
/** * @author yde * @date 2014-1-21 下午07:48:33 * @version V1.0 * @Description: TODO */ package com.ryan.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ryan.dao.UserDao; import com.ryan.entity.User; import com.ryan.service.UserService; @Service("userService") @Transactional public class UserServiceImpl extends BaseServiceImpl<User, Long> implements UserService { @Resource private UserDao userDao; @Resource public void setBaseDao(UserDao userDao){ super.setBaseDao(userDao); } @Override public User isExistByUsername(String username) { userDao.find(1L); return null; } }
15. UserController 控制器类
/** * @author yde * @date 2014-1-21 12:19:16 * @version V1.0 * @Description: 用户控制器 */ package com.ryan.controller; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.ryan.entity.User; import com.ryan.service.UserService; @Controller @RequestMapping(value = "/user") public class UserController{ @Resource private UserService userService; //列表 @RequestMapping(value = "/list", method = RequestMethod.GET) public String list(ModelMap model, Integer start, Integer limit) { List<User> users = userService.findList(start, limit); model.addAttribute("users", users); return "/user/user_list"; } //添加 @RequestMapping(value = "/add", method = RequestMethod.GET) public String add() { return "/user/user_add"; } //保存 @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(User user) { userService.save(user); return "redirect:list"; } //编辑 @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET) public String edit(@PathVariable Long id, ModelMap model){ User user = userService.find(id); model.addAttribute("user", user); return "/user/user_edit"; } //更新 @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(User user){ userService.update(user); return "redirect:list"; } //删除 @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) public String delete(@PathVariable Long id) { userService.delete(id); return "redirect:../list"; } }
16. 视图Jsp页面 user_list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘user_list.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 用户列表 [<a href="user/add">新增</a>]<br> <c:forEach var="user" items="${users}"> 用户名:<c:out value="${user.username}"></c:out> 密码: <c:out value="${user.password}"></c:out> <a href="user/edit/${user.id}">编辑</a>|<a href="user/delete/${user.id}">删除</a><br/> </c:forEach> </body> </html>
user_add.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘hello.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 新增 <form action="user/save" method="post"> 用户名:<input type="text" name="username" value="yangde" /><br/> 密码:<input type="password" name="password" value="111111" /><br/> <input type="submit" value="保存" /> </form> </body> </html>
user_edit.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘hello.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 编辑 <form action="user/update" method="post"> <input type="hidden" name="id" value="${user.id }" /> 用户名:<input type="text" name="username" value="${user.username }" /><br/> 密码:<input type="password" name="password" value="${user.password }" /><br/> <input type="submit" value="更新" /> </form> </body> </html>
17. 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"> <!-- 这个是 POM 的版本号,现在都是 4.0.0 的,必须得有,但不需要修改。 --> <modelVersion>4.0.0</modelVersion> <!-- Maven 项目的组织名、构件名、版本号 --> <groupId>com.ryan</groupId> <artifactId>demo</artifactId> <!-- 项目的打包方式,war 表示打包为 war 文件,默认为 jar,表示打包为 jar 文件。 --> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Maven Webapp Archetype</name> <url>http://maven.apache.org</url> <!-- 定义相关属性 --> <properties> <java-version>1.6</java-version> <junit-version>4.11</junit-version> <spring-version>3.2.2.RELEASE</spring-version> </properties> <dependencies> <!-- MySQL <scope>runtime</scope>作用域说明: compile:默认作用域,在编译、测试、运行时有效 test:对于测试时有效 runtime:对于测试、运行时有效 provided:对于编译、测试时有效,但在运行时无效 system:与 provided 类似,但依赖于系统资源 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</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-tx</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring-version}</version> </dependency> <!-- hibernate begin --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.0.Final</version> </dependency> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>4.0.4.Final</version> </dependency> <!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.0.Final</version> </dependency> --> <!-- hibernate end --> <!-- apache commons begin --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>20030825.184428</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>20030825.183949</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>2.1</version> </dependency> <!-- apache commons end --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>demo</finalName> <plugins> <!-- Ensures we are compiling at 1.6 level --> <!-- Compile --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>utf8</encoding> </configuration> </plugin> <!-- Tomcat <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat6-maven-plugin</artifactId> <version>2.2</version> </plugin>6228480332985787412 --> </plugins> <defaultGoal>compile</defaultGoal> </build> </project>
18. 最后发布到tomcat访问
19. sql 语句
CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT , `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=19 ROW_FORMAT=COMPACT ;
20. 如果没有用maven的话 引入jar包截图