1. 程式人生 > >ssh框架下 對資料庫的增刪改查

ssh框架下 對資料庫的增刪改查

1 、開發環境

Ø        MyEclipse6.0

Ø        JDK 1.6

Ø        Java EE 5.0

Ø        Tomcat6.0

Ø        Struts2.1

Ø        Spring2.0

Ø        Hibernate3

2 、為ssh做好準備

2.1下載包

Ø    Struts2.1包下載:http://struts.apache.org/download(現在最新版本估計已經是2.3.12了)

Ø    Hibernate3包下載:http://www.hibernate.org/

Ø    Spring2.0下載:http://www.springsource.org/download

2.2搭建開發環境

開啟MyEclipse,新建一個web project,如圖:(J2ee版本設為5.0)



點選Finish完成,建好的工程如圖:

設定好你的tomcat6的路徑即可,前提你要先安裝好tomcat哦。還有需要注意的一點是,看到目錄樹tomcat6.x下面的JDK了嗎?點選它,也要把tomcat的JDK設為jdk1.6才行,以與myeclipse一致。

       好了,工程已經建好了,下面就開始配置struts吧。配置之前先把struts的包下載下來哦,下載地址上面已經給出了。

3、配置Struts2.0

3.1基礎配置

1)使用struts只需要把下面五個引入即可,以後用到什麼jar包,再引入。


2)修改WEB-INF下的web.xml檔案,增加struts2的配置。增加程式碼如下:這些配置程式碼對於struts2是不變的,直接複製到web.xml即可。

<!--  配置Struts -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

3)新增struts配置檔案。 在WEB-INF/classes目錄下,新建struts.xml,模版如下:

<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTDStruts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
</struts>

這邊的2.0是要根據你自己的struts版本而定的。http://hi.baidu.com/albert02/item/e85abb44253ec336fa8960b5這個網址上面的錯誤就是因為版本的問題。

(以後的增刪改查的action會在這兩個struts標籤裡面寫,如下:

<package name="default" namespace="/" extends="struts-default">

  <action name="queryaction" class="queryaction"
   method="excute">
   <result name="success">query.jsp</result>
  </action>

  <action name="insertaction" class="insertaction"
   method="excute">
   <result name="success">insert.jsp</result>
  </action>

  <action name="deleteaction" class="deleteaction"
   method="excute">
   <result name="success">OK.jsp</result>
  </action>

  <action name="reviseaction" class="reviseaction"
   method="excute">
   <result name="success">OK.jsp</result>
  </action>

  <action name="showRecord" class="showRecord" method="excute">
   <result name="success">revise.jsp</result>
  </action>
 </package>

當然測試struts配置成功是不必加這些東西的)

4)現在把工程釋出到tomcat上去測試一下,在工程名字上點選右鍵,選擇MyEclipseàAdd and Removeproject Deployments,在開啟的窗口裡,點選Add,選擇我們之前配置好的tomcat6伺服器。釋出好了,啟動tomcat,如果啟動無異常,則說明配置成功。

4、配置Hibernate

4.1 基礎配置

1)  匯入最小jar包,即使用Hibernate3所必需的jar包。

2)   建立資料來源

(這邊add你的資料庫驅動包我的是

3)建立Hibernate配置檔案。在WEB-INF"calsses目錄下(工程的src包下)新建hibernate.cfg.xml。這是hibernate連線資料庫的配置檔案。這裡以連線My SQL為例:

a)首先給工程新增hibernate能力

這邊用我自己匯入的hibernate包MyEclipse自帶的不用。

這邊選擇剛剛建立的DB Driver

b)配置hibernate.cfg.xml檔案,我的配置檔案如下:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
 <property name="connection.username">root</property>
 <property name="connection.url">
  jdbc:mysql://localhost:3306/databaseoperation
 </property>
 <property name="dialect">
  org.hibernate.dialect.MySQLDialect
 </property>
 <property name="myeclipse.connection.profile">dbOperation</property>
 <property name="connection.driver_class">
  com.mysql.jdbc.Driver
 </property>
 <property name="show_sql">true</property>
 <property name="format_sql">true</property>
 <property name="connection.autocommit">true</property>   //這句是為了以後執行資料庫查詢的時候自動提交事務的
 <mapping resource="entity/User.hbm.xml" />

</session-factory>

</hibernate-configuration>

3)在web.xml檔案裡面加入以下內容:

<!-- 配置hibernate -->

 <filter>
  <filter-name>hibernateFilter</filter-name>
  <filter-class>
   org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  </filter-class>

  <init-param>
   <param-name>flushMode</param-name>
   <param-value>AUTO</param-value>
  </init-param>
 </filter>

  <filter-mapping>
  <filter-name>hibernateFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

5、配置Spring2.5

5.1 基礎配置

1)   匯入spring包。

2)    配置web.xml檔案。

在web.xml檔案裡面同樣加入:

<!--  配置Spring -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
 </context-param>

3   在src下面新建applicationContext.xml檔案。

</beans>

5.2整合Struts和Spring

Spring與Struts的整合其實就是把Struts的Action類交給Spring來管理.!

1)     匯入jar包。在Struts2.1.6lib目錄中找到struts2-spring-plugin-2.1.6.jar,引入到工程中。(剛開始已經匯入了)

2)       配置web.xml檔案。在web.xml中加入以下程式碼:

<!-- 整合spring和struts -->
 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>

3)這邊是我的增刪改查的action配置applicationContext.xml裡面的

<!-- 由於Struts -->
 <bean id="queryaction" class="action.QueryAction"
  scope="prototype">
  <property name="userService">
   <ref bean="userService" />
  </property>
 </bean>
 <bean id="insertaction" class="action.InsertAction"
  scope="prototype">
  <property name="userService">
   <ref bean="userService" />
  </property>
 </bean>
 <bean id="reviseaction" class="action.ReviseAction"
  scope="prototype">
  <property name="userService">
   <ref bean="userService" />
  </property>
 </bean>
 <bean id="deleteaction" class="action.DeleteAction"
  scope="prototype">
  <property name="userService">
   <ref bean="userService" />
  </property>
 </bean>
 <bean id="showRecord" class="action.showRecord"
  scope="prototype">
  <property name="userService">
   <ref bean="userService" />
  </property>
 </bean>

5.3整合Hibernate和Spring

Spring整合Hibernate主要是對hibernate的Session進行管理,包含Session的建立、提交、關閉的整個生命週期。Spring對事務的管理應用了AOP的技術。

1)  配置sessionFactory讓spring來建立Session。在applicationContext.xml中增加如下程式碼:

<bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="configLocation"
   value="classpath:hibernate.cfg.xml" />
 </bean>

2) 配置事務管理器。增加如下程式碼:

<bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

3)  對事務管理器進行事務設定。

<bean id="transactionBase"
  class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
  lazy-init="true" abstract="true">
  <property name="transactionManager" ref="transactionManager" />
  <property name="transactionAttributes">
   <props>
    <prop key="*">PROPAGATION_REQUIRED</prop>
   </props>
  </property>
 </bean>

4)事務運用到dao層下:applicationContext.xml裡面的

<!-- 由於hibernate -->
 <bean id="userDao" class="dao.UserDAOImpl">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>
 <bean id="userService" class="biz.UserServiceImpl">
  <property name="userDao">
   <ref bean="userDao" />
  </property>
 </bean>

這邊我會給出我建的專案的具體框架以及dao層的一個類檔案UserDAOImpl

package dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import entity.User;

public class UserDAOImpl extends HibernateDaoSupport implements IUserDAO {

 @SuppressWarnings("unchecked")
 public List<User> findAllUser() {
  String hql = "from User user order by user.id";
  return (List<User>) this.getHibernateTemplate().find(hql);
 }

 public User findUserById(Integer id) {
  User user = (User) this.getHibernateTemplate().get(User.class, id);
  return user;
 }

 public void removeUser(int id) {
//  final String hql = "delete User u where u.id= " + id;
//  Integer count = (Integer) getHibernateTemplate().execute(
//    new HibernateCallback() {
//     public Object doInHibernate(Session session)
//       throws HibernateException, SQLException {
//      int deletedEntities = session.createQuery(hql)
//        .executeUpdate();
//      return deletedEntities;
//     }
//    });
   User user = (User) this.getHibernateTemplate().get(User.class, id);
   this.getHibernateTemplate().delete(user);
 }

 public void saveUser(User user) {
  this.getHibernateTemplate().save(user);
 }

 public void updateUser(User user) {
  this.getHibernateTemplate().update(user);
 }
}

總結:

具體的SSH配置就這些了,其他的就是寫實現增刪改查action的類了我的專案架構如下: