首页 > 代码库 > Struts2+Hibernate+Spring框架实现增删改查

Struts2+Hibernate+Spring框架实现增删改查

一、添加3个框架的JAR包,完成后写配置文件;

1、web配置文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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" id="WebApp_ID" version="3.0">
 3   <display-name>oa</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   <filter>
13     <filter-name>struts2</filter-name>
14     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
15   </filter>
16   <filter-mapping>
17     <filter-name>struts2</filter-name>
18     <url-pattern>*.action</url-pattern>
19   </filter-mapping>
20   <listener>
21     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
22   </listener>
23   <context-param>
24     <param-name>contextConfigLocation</param-name>
25     <param-value>classpath:applicationContext.xml</param-value>
26   </context-param>
27 </web-app>
View Code

2、Struts2配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
 3 <struts>
 4 
 5     <!-- 配置开发模式 -->
 6     <constant name="struts.devMode" value="true" />
 7     <!-- 把扩展名改为action -->
 8     <constant name="struts.action.extension" value="action" />
 9     <!-- 把主题改为simple -->
10 
11 
12     <package name="default" namespace="/" extends="struts-default">
13         <action name="test-*" class="testAction" method="{1}">
14             <result name="list">/WEB-INF/jsp/test/test.jsp</result>
15             <result name="editUI">/WEB-INF/jsp/test/editUI.jsp</result>
16             <result name="addUI">/WEB-INF/jsp/test/addUI.jsp</result>
17             <result name="toList" type="redirectAction">test-list</result>
18         </action>
19     </package>
20 
21 </struts>    
View Code

3、Hibernate配置文件

 1 <?xml version=‘1.0‘ encoding=‘UTF-8‘?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4           "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 <!-- Generated by MyEclipse Hibernate Tools. -->
 6 <hibernate-configuration>
 7 
 8     <session-factory>
 9 
10         <property name="hbm2ddl.auto">update</property>
11         <property name="show_sql">true</property>
12 
13         <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
14         <!-- <property name="connection.url">jdbc:mysql://127.0.0.1:3306/oa</property> 
15             <property name="connection.username">root</property> <property name="connection.password">admin</property> 
16             <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
17             <property name="myeclipse.connection.profile">mysql</property> -->
18 
19         <mapping resource="oa/test/model/Model.hbm.xml" />
20     </session-factory>
21 
22 </hibernate-configuration>
View Code

4、jdbc.properites文件

1 driver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://127.0.0.1:3306/oa
3 user=root
4 password=admin
View Code

5、applicationContext.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" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
 6         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
 7         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
 8 
 9     <context:component-scan base-package="oa.test,oa.hibernate"></context:component-scan>
10     <context:property-placeholder location="classpath:jdbc.properties" />
11 
12 
13     <bean id="sessionFactory"
14         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
15         <property name="configLocation" value="classpath:hibernate.cfg.xml">
16         </property>
17         <property name="dataSource">
18             <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
19                 <property name="jdbcUrl" value="${url}" />
20                 <property name="driverClass" value="${driver}" />
21                 <property name="user" value="${user}" />
22                 <property name="password" value="${password}" />
23                 <!-- 其他配置 -->
24                 <!-- 初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
25                 <property name="initialPoolSize" value="3" />
26                 <!-- 连接池中保留的最小连接数。Default: 3 -->
27                 <property name="minPoolSize" value="3" />
28                 <!-- 连接池中保留的最大连接数。Default: 15 -->
29                 <property name="maxPoolSize" value="5" />
30                 <!-- 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
31                 <property name="acquireIncrement" value="3" />
32                 <!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 
33                     0 -->
34                 <property name="maxStatements" value="8" />
35                 <!-- maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 
36                     0 -->
37                 <property name="maxStatementsPerConnection" value="5" />
38                 <!-- 最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
39                 <property name="maxIdleTime" value="1800" />
40 
41             </bean>
42         </property>
43     </bean>
44     <bean id="transactionManager"
45         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
46         <property name="sessionFactory" ref="sessionFactory" />
47     </bean>
48     <tx:annotation-driven transaction-manager="transactionManager" />
49 </beans>
View Code

 二、测试,使用JUnit4测试;

1、添加一个TestAction类:

 1 package cn.feeaooa.oa;
 2 
 3 
 4 import javax.annotation.Resource;
 5 
 6 import org.springframework.context.annotation.Scope;
 7 import org.springframework.stereotype.Controller;
 8 
 9 import com.opensymphony.xwork2.ActionSupport;
10 
11 @SuppressWarnings("serial")
12 @Controller
13 @Scope("prototype")
14 public class TestAction extends ActionSupport {
15     
16     @Resource
17     private TestService testService;
18     
19     @Override
20     public String execute() throws Exception {
21         // TODO 自动生成的方法存根
22         System.out.println("TestAction.execute()");
23         testService.saveTowUser();
24         return "success";
25     }
26 }
View Code

 

2、添加一个TestSpring类,用于测试JavaBean 

 1 package cn.feeaooa.oa;
 2 
 3 import org.hibernate.SessionFactory;
 4 import org.junit.Test;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.support.ClassPathXmlApplicationContext;
 7 
 8 
 9 public class SpringTest {
10 
11     private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
12     
13     @SuppressWarnings("unused")
14     @Test
15     public void testBean() throws Exception{
16         TestAction testAction = (TestAction)ac.getBean("testAction");
17         System.out.println("SpringTest.testBean()");
18     }
19     
20     @Test
21     public void testSessionFactory() throws Exception{
22         SessionFactory sessionFactory = (SessionFactory)ac.getBean("sessionFactory");
23         System.out.println(sessionFactory);
24     }
25     
26     @Test
27     public void testTransaction() throws Exception{
28         TestService testService = (TestService)ac.getBean("testService");
29         testService.saveTowUser();
30     }
31 }
View Code

 

...

三、完成所有测试后,写数据库的操作类;

1、添加一个BaseDAO接口:

 1 package cn.oa.base;
 2 
 3 import java.util.List;
 4 
 5 
 6 public interface BaseDAO<T> {
 7     /**
 8      * 保存实体
 9      * @param entity
10      */
11     void save(T entity);
12     /**
13      * 删除实体
14      * @param id
15      */
16     void delete(Long id);
17     /**
18      * 更新实体
19      * @param entity
20      */
21     void update(T entity);
22     /**
23      * 按id查询,返回对象
24      * @param id
25      * @return
26      */
27     T getById(Long id);
28     /**
29      * 按多个id查询,返回数组
30      * @param ids
31      * @return
32      */
33     List<T> getByIds(Long[] ids);
34     /**
35      * 查询所有实体
36      * @return
37      */
38     List<T> findAll();
39     
40 }
BaseDAO接口

 

2、添加BaseDAOImpl对BaseDAO接口实现

 1 package cn.oa.base;
 2 
 3 import java.lang.reflect.ParameterizedType;
 4 import java.util.List;
 5 
 6 import javax.annotation.Resource;
 7 
 8 import org.hibernate.Session;
 9 import org.hibernate.SessionFactory;
10 import org.hibernate.sql.Update;
11 
12 @SuppressWarnings("unchecked")
13 public abstract class BaseDAOImpl<T> implements BaseDAO<T> {
14 
15     @Resource
16     private SessionFactory sessionFactory;
17     private Class<T> clazz;
18 
19     public BaseDAOImpl() {
20         // 使用反射技术得到T的真实类型
21         ParameterizedType pt = (ParameterizedType) this.getClass()
22                 .getGenericSuperclass(); // 获取当前new的对象的 泛型的父类 类型
23         this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; // 获取第一个类型参数的真实类型
24         System.out.println("clazz ---> " + clazz);
25     }
26     /**
27      * 获取可用的session
28      * @return
29      */
30     protected Session getSession() {
31         return sessionFactory.getCurrentSession();
32     }
33     /**
34      * 保存实体
35      */
36     public void save(T entity) {
37         getSession().save(entity);
38     }
39     /**
40      * 删除实体
41      */
42     public void delete(Long id) {
43         Object obj = getById(id);
44         if (obj != null) {
45             getSession().delete(obj);
46         }
47     }
48     /**
49      * 更新实体
50      * @param entity
51      */
52     public void update(T entity) {
53         getSession().update(entity);
54     }
55     /**
56      * 按id查询
57      */
58     public T getById(Long id) {
59         return (T) getSession().get(clazz, id);
60     }
61     /**
62      * 按id查询
63      */
64     public List<T> getByIds(Long[] ids) {
65         return getSession().createQuery(//
66                 "FROM User WHERE id IN(:ids)")//
67                 .setParameterList("ids", ids).list();
68     }
69     /**
70      * 查询所有实体
71      */
72     public List<T> findAll() {
73         return getSession().createQuery(//
74                 "FROM " + clazz.getSimpleName())//
75                 .list();
76     }
77 }
View Code

 

3、设计对象模型类

 1 package oa.test.model;
 2 
 3 public class Model {
 4     private Long id;
 5     private String name;
 6     public Long getId() {
 7         return id;
 8     }
 9     public void setId(Long id) {
10         this.id = id;
11     }
12     public String getName() {
13         return name;
14     }
15     public void setName(String name) {
16         this.name = name;
17     }
18 }
View Code

 

4、添加模型类配置文件

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3                                    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <hibernate-mapping package="oa.test.model">
 5  <class name="Model" table="my_Model">
 6   <id name="id">
 7    <generator class="native"/>
 8   </id>
 9   <property name="name" length="40"/>
10  </class>
11 </hibernate-mapping>
View Code

 

5、添加接口ModelDAO类

1 package oa.test.dao;
2 
3 import oa.test.model.Model;
4 import cn.oa.base.BaseDAO;
5 
6 public interface ModelDAO extends BaseDAO<Model> {
7     
8 }
View Code

 

6、添加模型ModelDAOImpl类对ModelDAO接口实现

 1 package oa.test.dao.Impl;
 2 
 3 import org.springframework.stereotype.Repository;
 4 
 5 import oa.test.dao.ModelDAO;
 6 import oa.test.model.Model;
 7 import cn.oa.base.BaseDAOImpl;
 8 
 9 @Repository
10 public class ModelDAOImpl extends BaseDAOImpl<Model> implements ModelDAO {
11 
12     
13 }
View Code

 

7、添加事物类接口ModelService

 1 package oa.test.service;
 2 
 3 import java.util.List;
 4 
 5 import oa.test.model.Model;
 6 
 7 public interface ModelService {
 8     List<Model> findAll();
 9     void delete(Long id);
10     void save(Model model);
11     Model getById(Long id);
12     void update(Model model);
13 }
View Code

 8、在Action类中接受页面请求及对请求的实现

 1 package oa.test.action;
 2 
 3 import java.util.List;
 4 
 5 import javax.annotation.Resource;
 6 
 7 import oa.test.model.Model;
 8 import oa.test.service.ModelService;
 9 
10 import org.springframework.context.annotation.Scope;
11 import org.springframework.stereotype.Controller;
12 
13 import com.opensymphony.xwork2.ActionContext;
14 import com.opensymphony.xwork2.ActionSupport;
15 import com.opensymphony.xwork2.ModelDriven;
16 
17 @SuppressWarnings("serial")
18 @Controller
19 @Scope("prototype")
20 public class TestAction extends ActionSupport implements ModelDriven<Model> {
21     
22     @Resource
23     private ModelService modelService;
24     
25     private Model model = new Model();
26     
27     public Model getModel() {
28         return model;
29     }
30     
31     public void setModel(Model model){
32         this.model = model;
33     }
34     
35     public String list() throws Exception{
36         List<Model> list = modelService.findAll();
37         ActionContext.getContext().put("list", list);
38         return "list";
39     }
40     
41     public String addUI() throws Exception{
42         return "addUI";
43     }
44     
45     public String add() throws Exception{
46         modelService.save(model);
47         return "toList";
48     }
49     
50     public String del() throws Exception{
51         modelService.delete(model.getId());
52         return "toList";
53     }
54     
55     public String editUI() throws Exception{
56         model = modelService.getById(model.getId());
57         ActionContext.getContext().getValueStack().push(model);
58         return "editUI";
59     }
60     
61     public String edit() throws Exception{
62         modelService.update(model);
63         List<Model> list = modelService.findAll();
64         ActionContext.getContext().put("list", list);
65         return "toList";
66     }
67 }
View Code

 

 9、添加list.jsp页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib prefix="s" uri="/struts-tags" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="http://www.mamicode.com/">
12     
13     <title>My JSP ‘test.jsp‘ starting page</title>
14     
15     <meta http-equiv="pragma" content="no-cache">
16     <meta http-equiv="cache-control" content="no-cache">
17     <meta http-equiv="expires" content="0">    
18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19     <meta http-equiv="description" content="This is my page">
20     <!--
21     <link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css">
22     -->
23 
24   </head>
25   
26   <body>
27     This is my JSP page. <br>adasd<br>
28     <table cellspacing="1" cellpadding="1" border="1" style="text-align: center;margin: 0 auto;">
29         <tr>
30             <th width="150">编号</th><th width="150">名称</th><th width="150">操作</th>
31         </tr>
32         <s:iterator value="http://www.mamicode.com/#list">
33             <tr>
34                 <td>${id}</td>
35                 <td>${name}</td>
36                 <td><a href="http://www.mamicode.com/test-editUI.action?id=${id}">修改</a>/<a href="http://www.mamicode.com/test-del.action?id=${id}" onclick="return confirm(‘确定要删除吗?‘)">删除</a></td>
37             </tr>
38         </s:iterator>
39         <tr><td></td><td></td>
40             <td><a href="http://www.mamicode.com/test-addUI.action">添加</a></td>
41         </tr>
42     </table>
43   </body>
44 </html>
View Code

 

效果:

 

增删该查是完成了,但是还有一个问题就是中文乱码问题,明天再看看Hibernate配置。