SSH框架學習(四、在struts和spring基礎上加入hibernate)

原文轉自:http://blog.csdn.net/wuyt2008/article/details/8243544

Hibernate有很機械的pojo類和hbm文件要寫,這部分用myeclipse來做,能省不少事情,終於又感覺到myeclipse的好處了。


1、先在mysql裏面建個表

  1. CREATE TABLE `t_user` (  
  2.   `pk_user_id` bigint(20) NOT NULL AUTO_INCREMENT,  
  3.   `login_name` varchar(45) DEFAULT NULL,  
  4.   `email` varchar(45) DEFAULT NULL,  
  5.   `passwordvarchar(45) DEFAULT NULL,  
  6.   PRIMARY KEY (`pk_user_id`)  
  7. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

2、讓myeclipse連接到數據庫,還會幫我們自動生成hibernate的配置文件,和一個sessionFactory類。


3、用myeclipse生成實體類和映射配置文件,在myeclipse的db browser裏面,打開數據庫,選中表。

最後會生成這樣一堆文件

整理一下,我是這麼放的


4、把myeclipse添加的lib引用去掉,換成hibernate4。

就是這兩個hibernate 3.3的,去掉。

hibernate最新版是4.1.8,下載地址http://sourceforge.net/projects/hibernate/files/hibernate4/

解壓開後,在lib目錄下有個叫required的目錄,下面放的是最基本的包,這個我喜歡,比struts和spring做的好。

引入這些包就好了

此外還需要mysql的連接包,最新版本5.1.22,下載地址:http://www.mysql.com/downloads/connector/j/


5、現在開始來修改,從web頁面開始


在網站根目錄下,增加一個user目錄,下面添加一個add.jsp文件。

[html] view plaincopy
  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.     <title>My JSP 'add.jsp' starting page</title>    
  12.     <meta http-equiv="pragma" content="no-cache">  
  13.     <meta http-equiv="cache-control" content="no-cache">  
  14.   </head>  
  15.   <body>  
  16.     <form name="form1" method="post" action="user!add.action">  
  17.       <p>  
  18.         <label for="loginname">loginname</label>  
  19.         <input type="text" name="loginname">  
  20.       </p>  
  21.       <p>  
  22.         <label for="email">email</label>  
  23.         <input type="text" name="email">  
  24.       </p>  
  25.       <p>  
  26.         <label for="password">password</label>  
  27.         <input type="text" name="password">  
  28.       </p>  
  29.       <p>  
  30.         <input type="submit" name="submit" value="提交">  
  31.       </p>  
  32.     </form>  
  33.   This is my JSP page. <br>  
  34.   </body>  
  35. </html>  


這個頁面,將內容提交到了UserAction類的add方法,現在來修改UserAction類。

UserAction類裏面要添加add方法,和接收頁面信息的屬性及方法。

[java] view plaincopy
  1. package demo.myssh.action;  
  2.   
  3. import com.opensymphony.xwork2.ActionSupport;  
  4. import demo.myssh.business.UserService;  
  5. import demo.myssh.model.User;  
  6.   
  7. @SuppressWarnings("serial")  
  8. public class UserAction extends ActionSupport {  
  9.   
  10.     @Override  
  11.     public String execute() throws Exception {  
  12.   
  13.         this.addActionMessage("UserAction working");  
  14.         // this.addActionMessage("hello world.");  
  15.         this.addActionMessage(userService.doing());// 修改下,確認注入成功。  
  16.   
  17.         return ActionSupport.SUCCESS;  
  18.     }  
  19.   
  20.     // 注入用屬性  
  21.     private UserService userService;  
  22.   
  23.     // 注入用的方法  
  24.     public void setUserService(UserService userService) {  
  25.         this.userService = userService;  
  26.     }  
  27.   
  28.   
  29.     public String add() throws Exception {  
  30.         userService.save(new User(loginname, email, password));  
  31.         return ActionSupport.SUCCESS;  
  32.     }  
  33.   
  34.     private String loginname;  
  35.     private String email;  
  36.     private String password;  
  37.   
  38.     public void setLoginname(String loginname) {  
  39.         this.loginname = loginname;  
  40.     }  
  41.   
  42.     public void setEmail(String email) {  
  43.         this.email = email;  
  44.     }  
  45.   
  46.     public void setPassword(String password) {  
  47.         this.password = password;  
  48.     }  
  49. }  

這裏面,用到了UserService類裏面的save方法,繼續修改UserService。

[java] view plaincopy
  1. package demo.myssh.business;  
  2.   
  3. import demo.myssh.dao.UserDAO;  
  4. import demo.myssh.model.User;  
  5.   
  6. public class UserService {  
  7.   
  8.     public String doing() {  
  9.         return "UserService working";  
  10.     }  
  11.   
  12.     private UserDAO userDAO;  
  13.   
  14.     public void setUserDAO(UserDAO userDAO) {  
  15.         this.userDAO = userDAO;  
  16.     }  
  17.   
  18.     public void save(User user) {  
  19.         userDAO.save(user);  
  20.     }  
  21. }  

UserDAO這個類不需要多少修改,只需要把裏面日誌有關的地方去掉就可以了。因爲,我沒有引入那個類。大家都喜歡用log4j,打算之後加入log4j。

[java] view plaincopy
  1. package demo.myssh.dao;  
  2.   
  3. import java.util.List;  
  4. import org.hibernate.LockMode;  
  5. import org.hibernate.Query;  
  6. import org.hibernate.criterion.Example;  
  7. import demo.myssh.model.User;  
  8.   
  9. public class UserDAO extends BaseHibernateDAO {  
  10.   
  11.     // property constants  
  12.     public static final String LOGIN_NAME = "loginName";  
  13.     public static final String EMAIL = "email";  
  14.     public static final String PASSWORD = "password";  
  15.   
  16.     public void save(User transientInstance) {  
  17.   
  18.         try {  
  19.             getSession().save(transientInstance);  
  20.   
  21.         } catch (RuntimeException re) {  
  22.   
  23.             throw re;  
  24.         }  
  25.     }  
  26.   
  27.     public void delete(User persistentInstance) {  
  28.   
  29.         try {  
  30.             getSession().delete(persistentInstance);  
  31.   
  32.         } catch (RuntimeException re) {  
  33.   
  34.             throw re;  
  35.         }  
  36.     }  
  37.   
  38.     public User findById(java.lang.Long id) {  
  39.   
  40.         try {  
  41.             User instance = (User) getSession().get("User", id);  
  42.             return instance;  
  43.         } catch (RuntimeException re) {  
  44.   
  45.             throw re;  
  46.         }  
  47.     }  
  48.   
  49.     public List findByExample(User instance) {  
  50.   
  51.         try {  
  52.             List results = getSession().createCriteria("User")  
  53.                     .add(Example.create(instance)).list();  
  54.   
  55.             return results;  
  56.         } catch (RuntimeException re) {  
  57.   
  58.             throw re;  
  59.         }  
  60.     }  
  61.   
  62.     public List findByProperty(String propertyName, Object value) {  
  63.   
  64.         try {  
  65.             String queryString = "from User as model where model."  
  66.                     + propertyName + "= ?";  
  67.             Query queryObject = getSession().createQuery(queryString);  
  68.             queryObject.setParameter(0, value);  
  69.             return queryObject.list();  
  70.         } catch (RuntimeException re) {  
  71.   
  72.             throw re;  
  73.         }  
  74.     }  
  75.   
  76.     public List findByLoginName(Object loginName) {  
  77.         return findByProperty(LOGIN_NAME, loginName);  
  78.     }  
  79.   
  80.     public List findByEmail(Object email) {  
  81.         return findByProperty(EMAIL, email);  
  82.     }  
  83.   
  84.     public List findByPassword(Object password) {  
  85.         return findByProperty(PASSWORD, password);  
  86.     }  
  87.   
  88.     public List findAll() {  
  89.   
  90.         try {  
  91.             String queryString = "from User";  
  92.             Query queryObject = getSession().createQuery(queryString);  
  93.             return queryObject.list();  
  94.         } catch (RuntimeException re) {  
  95.   
  96.             throw re;  
  97.         }  
  98.     }  
  99.   
  100.     public User merge(User detachedInstance) {  
  101.   
  102.         try {  
  103.             User result = (User) getSession().merge(detachedInstance);  
  104.   
  105.             return result;  
  106.         } catch (RuntimeException re) {  
  107.   
  108.             throw re;  
  109.         }  
  110.     }  
  111.   
  112.     public void attachDirty(User instance) {  
  113.   
  114.         try {  
  115.             getSession().saveOrUpdate(instance);  
  116.   
  117.         } catch (RuntimeException re) {  
  118.   
  119.             throw re;  
  120.         }  
  121.     }  
  122.   
  123.     public void attachClean(User instance) {  
  124.   
  125.         try {  
  126.             getSession().lock(instance, LockMode.NONE);  
  127.   
  128.         } catch (RuntimeException re) {  
  129.   
  130.             throw re;  
  131.         }  
  132.     }  
  133. }  

BaseHibernateDAO 不用改,沿用

[java] view plaincopy
  1. package demo.myssh.dao;  
  2.   
  3. import org.hibernate.Session;  
  4.   
  5.   
  6. public class BaseHibernateDAO implements IBaseHibernateDAO {  
  7.       
  8.     public Session getSession() {  
  9.         return HibernateSessionFactory.getSession();  
  10.     }  
  11.       
  12. }  

IBaseHibernateDAO 不用改,沿用

[java] view plaincopy
  1. package demo.myssh.dao;  
  2.   
  3. import org.hibernate.Session;  
  4.   
  5. public interface IBaseHibernateDAO {  
  6.     public Session getSession();  
  7. }  

HibernateSessionFactory這個類要修改,因爲hibernate 4 創建session的方法變了。

[java] view plaincopy
  1. package demo.myssh.dao;  
  2.   
  3. import org.hibernate.HibernateException;  
  4. import org.hibernate.Session;  
  5. import org.hibernate.cfg.Configuration;  
  6. import org.hibernate.service.ServiceRegistry;  
  7. import org.hibernate.service.ServiceRegistryBuilder;  
  8.   
  9. public class HibernateSessionFactory {  
  10.   
  11.     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";  
  12.     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();  
  13.     private static Configuration configuration = new Configuration();  
  14.     private static org.hibernate.SessionFactory sessionFactory;  
  15.     private static String configFile = CONFIG_FILE_LOCATION;  
  16.     private static ServiceRegistry serviceRegistry;  
  17.   
  18.     static {  
  19.         try {  
  20.             //hibernate 3 的方法  
  21.             // configuration.configure(configFile);  
  22.             // sessionFactory = configuration.buildSessionFactory();  
  23.   
  24.             //hibernate 4 的方法  
  25.             serviceRegistry = new ServiceRegistryBuilder().applySettings(  
  26.                     configuration.configure().getProperties())  
  27.                     .buildServiceRegistry();  
  28.             sessionFactory = configuration.buildSessionFactory(serviceRegistry);  
  29.         } catch (HibernateException e) {  
  30.             System.err.println("%%%% Error Creating SessionFactory %%%%");  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34.   
  35.     private HibernateSessionFactory() {  
  36.     }  
  37.   
  38.     public static Session getSession() throws HibernateException {  
  39.         Session session = (Session) threadLocal.get();  
  40.   
  41.         if (session == null || !session.isOpen()) {  
  42.             if (sessionFactory == null) {  
  43.                 rebuildSessionFactory();  
  44.             }  
  45.             session = (sessionFactory != null) ? sessionFactory.openSession()  
  46.                     : null;  
  47.             threadLocal.set(session);  
  48.         }  
  49.   
  50.         return session;  
  51.     }  
  52.   
  53.   
  54.     public static void rebuildSessionFactory() {  
  55.         try {  
  56.             // configuration.configure(configFile);  
  57.             // sessionFactory = configuration.buildSessionFactory();  
  58.   
  59.             serviceRegistry = new ServiceRegistryBuilder().applySettings(  
  60.                     configuration.configure().getProperties())  
  61.                     .buildServiceRegistry();  
  62.             sessionFactory = configuration.buildSessionFactory(serviceRegistry);  
  63.         } catch (HibernateException e) {  
  64.             System.err.println("%%%% Error Creating SessionFactory %%%%");  
  65.             e.printStackTrace();  
  66.         }  
  67.     }  
  68.   
  69.   
  70.     public static void closeSession() throws HibernateException {  
  71.         Session session = (Session) threadLocal.get();  
  72.         threadLocal.set(null);  
  73.   
  74.         if (session != null) {  
  75.             session.close();  
  76.         }  
  77.     }  
  78.   
  79.   
  80.     public static org.hibernate.SessionFactory getSessionFactory() {  
  81.         return sessionFactory;  
  82.     }  
  83.   
  84.     public static void setConfigFile(String configFile) {  
  85.         HibernateSessionFactory.configFile = configFile;  
  86.         sessionFactory = null;  
  87.     }  
  88.   
  89.   
  90.     public static Configuration getConfiguration() {  
  91.         return configuration;  
  92.     }  
  93.   
  94. }  

User實體類不用改,不過還是貼出來吧。

[java] view plaincopy
  1. package demo.myssh.model;  
  2.   
  3. public class User implements java.io.Serializable {  
  4.   
  5.     private static final long serialVersionUID = -8290754809696899650L;  
  6.     private Long userID;  
  7.     private String loginName;  
  8.     private String email;  
  9.     private String password;  
  10.   
  11.   
  12.     /** default constructor */  
  13.     public User() {  
  14.     }  
  15.   
  16.     /** full constructor */  
  17.     public User(String loginName, String email, String password) {  
  18.         this.loginName = loginName;  
  19.         this.email = email;  
  20.         this.password = password;  
  21.     }  
  22.   
  23.     // Property accessors  
  24.   
  25.     public Long getUserID() {  
  26.         return this.userID;  
  27.     }  
  28.   
  29.     public void setUserID(Long userID) {  
  30.         this.userID = userID;  
  31.     }  
  32.   
  33.     public String getLoginName() {  
  34.         return this.loginName;  
  35.     }  
  36.   
  37.     public void setLoginName(String loginName) {  
  38.         this.loginName = loginName;  
  39.     }  
  40.   
  41.     public String getEmail() {  
  42.         return this.email;  
  43.     }  
  44.   
  45.     public void setEmail(String email) {  
  46.         this.email = email;  
  47.     }  
  48.   
  49.     public String getPassword() {  
  50.         return this.password;  
  51.     }  
  52.   
  53.     public void setPassword(String password) {  
  54.         this.password = password;  
  55.     }  
  56.   
  57. }  

還有映射文件,記得添加下package,讓hibernate能找到實體類

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC    
  3.         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    
  4.         "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">  
  5.   
  6. <hibernate-mapping  package="demo.myssh.model">  
  7.     <class name="User" table="t_user" catalog="myssh">  
  8.         <id name="userID" type="java.lang.Long">  
  9.             <column name="pk_user_id" />  
  10.             <generator class="identity"></generator>  
  11.         </id>  
  12.         <property name="loginName" type="java.lang.String">  
  13.             <column name="login_name"  length="45"/>  
  14.         </property>  
  15.         <property name="email" type="java.lang.String">  
  16.             <column name="email"  length="45"/>  
  17.         </property>  
  18.         <property name="password" type="java.lang.String">  
  19.             <column name="password"  length="45"/>  
  20.         </property>  
  21.     </class>  
  22. </hibernate-mapping>  

然後是hibernate的配置文件,

[html] view plaincopy
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.     "-//Hibernate/Hibernate Configuration DTD//EN"  
  4.     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.     <session-factory>  
  8.         <!-- properties -->  
  9.         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>  
  10.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
  11.   
  12.         <property name="connection.url">jdbc:mysql://localhost:3306/myssh</property>  
  13.         <property name="connection.username">root</property>  
  14.         <property name="connection.password"></property>  
  15.   
  16.         <property name="connection.autocommit">true</property>  
  17.   
  18.         <!-- mapping files -->  
  19.         <mapping resource="demo/myssh/model/User.hbm.xml" />  
  20.     </session-factory>  
  21. </hibernate-configuration>  
這裏注意,要添加autocommit屬性,因爲是用的myeclipse提供的sessionFactory。mapping路徑也不要忘了。


最後,修改spring的配置文件applicationContext.xml,提供注入

[html] view plaincopy
  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:util="http://www.springframework.org/schema/util"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  7.      http://www.springframework.org/schema/util  
  8.      http://www.springframework.org/schema/util/spring-util-3.0.xsd">  
  9.   
  10.   
  11.     <bean id="userAction" class="demo.myssh.action.UserAction">  
  12.         <property name="userService" ref="userService" />  
  13.     </bean>  
  14.   
  15.     <bean id="userService" class="demo.myssh.business.UserService">  
  16.         <property name="userDAO" ref="userDAO"></property>  
  17.     </bean>  
  18.   
  19.     <bean id="userDAO" class="demo.myssh.dao.UserDAO">  
  20.     </bean>  
  21.       
  22. </beans>  

運行訪問:http://localhost:8080/user/add.jsp

提交以後,又轉回index.jsp,查看數據庫

大功告成,最基本簡單的ssh框架搭建終於完成。


程序結構再貼下



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章