spring+hibernate+struts2+compass整合

来源:互联网 发布:bobble是什么软件 编辑:程序博客网 时间:2024/06/05 20:27

需要引入compass的相关jar包:

compass-2.1.0.jar

compass-index-patch.jar

lucene-core.jar

lucene-highlighter.jar

paoding-analysis.jar

=======================================================

建表语句:


1 CREATE TABLE `product` (2   `id` int(11) NOT NULL AUTO_INCREMENT,3   `name` varchar(80) COLLATE utf8_unicode_ci DEFAULT NULL,4   `price` double(6,0) DEFAULT NULL,5   `brand` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,6   `description` varchar(2000) COLLATE utf8_unicode_ci DEFAULT NULL,7   PRIMARY KEY (`id`)8 ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

注:这是我在mySQL中建立的product表,与本项目的表有一个地方有区别:id的类型

项目中的是varchar(40),用的uuid的策略。更详细的信息请看:/compass1/src/com/v512/example/model/Product.hbm.xml

=======================================================

/compass1/src/com/v512/example/action/ProductAction.java


 1 package com.v512.example.action; 2  3 import java.util.List; 4  5 import com.opensymphony.xwork2.ActionSupport; 6 import com.v512.example.model.Product; 7 import com.v512.example.service.ProductManager; 8 import org.apache.struts2.ServletActionContext; 9 10 public class ProductAction extends ActionSupport {11 12     private static final long serialVersionUID = 3795048906805728732L;13     private ProductManager productManager;14     private Product product;15     private String queryString;16 17     public void setQueryString(String queryString) {18         this.queryString = queryString;19     }20 21     public Product getProduct() {22         return product;23     }24 25     public void setProduct(Product product) {26         this.product = product;27     }28 29     public void setProductManager(ProductManager productManager) {30         this.productManager = productManager;31     }32 33     public String insert() {34         productManager.insertProduct(product);35         return SUCCESS;36     }37 38     public String search() {39         List results = productManager.searchProducts(queryString);40         System.out.println(results.size());41         ServletActionContext.getRequest()42                 .setAttribute("searchresults", results);43         return SUCCESS;44     }45 46 }

/compass1/src/com/v512/example/dao/ProductDao.java


 1 package com.v512.example.dao; 2  3 import java.util.List; 4  5 import com.v512.example.model.Product; 6  7 public interface ProductDao { 8     public void create(Product p); 9 10     public Product getProduct(String id);11 12     public List getProducts();13 14     public void update(Product product);15 16     public void remove(String id);17 18 }

/compass1/src/com/v512/example/dao/hibernate/ProductDaoHibernate.java


 1 package com.v512.example.dao.hibernate; 2  3 import java.util.List; 4  5 import com.v512.example.dao.ProductDao; 6 import com.v512.example.model.Product; 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 8  9 public class ProductDaoHibernate extends HibernateDaoSupport implements10         ProductDao {11 12     public void create(Product p) {13         getHibernateTemplate().save(p);14 15     }16 17     public Product getProduct(String id) {18         return (Product) getHibernateTemplate().get(Product.class, id);19     }20 21     public List getProducts() {22         return getHibernateTemplate().find("from Product order by id desc");23     }24 25     public void remove(String id) {26         getHibernateTemplate().delete(getProduct(id));27 28     }29 30     public void update(Product product) {31         getHibernateTemplate().saveOrUpdate(product);32 33     }34 35 }

/compass1/src/com/v512/example/model/Product.java

在实体类中注入compass


 1 package com.v512.example.model; 2  3 import org.compass.annotations.*; 4  5 /** 6  * Product entity. 7  *  8  * @author MyEclipse Persistence Tools 9  */10 @Searchable11 public class Product implements java.io.Serializable {12 13     // Fields14 //在实体类中注入compass15     @SearchableId16     private String id;17     @SearchableProperty(name = "name")18     private String name;19     @SearchableProperty(name = "price")20     private Double price;21     @SearchableProperty(name = "brand")22     private String brand;23     @SearchableProperty(name = "description")24     private String description;25 26     // Constructors27 28     /** default constructor */29     public Product() {30     }31 32     /** full constructor */33     public Product(String name, Double price, String brand, String description) {34         this.name = name;35         this.price = price;36         this.brand = brand;37         this.description = description;38     }39 40     // Property accessors41 42     public String getId() {43         return this.id;44     }45 46     public void setId(String id) {47         this.id = id;48     }49 50     public String getName() {51         return this.name;52     }53 54     public void setName(String name) {55         this.name = name;56     }57 58     public Double getPrice() {59         return this.price;60     }61 62     public void setPrice(Double price) {63         this.price = price;64     }65 66     public String getBrand() {67         return this.brand;68     }69 70     public void setBrand(String brand) {71         this.brand = brand;72     }73 74     public String getDescription() {75         return this.description;76     }77 78     public void setDescription(String description) {79         this.description = description;80     }81 82 }
复制代码

/compass1/src/com/v512/example/model/Product.hbm.xml

复制代码
 1 <?xml version="1.0" encoding="utf-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <!--  5     Mapping file autogenerated by MyEclipse Persistence Tools 6 --> 7 <hibernate-mapping> 8     <class name="com.v512.example.model.Product" table="PRODUCT" schema="SCOTT"> 9         <id name="id" type="java.lang.String">10             <column name="ID" length="40" />11             <generator class="uuid.hex" />12         </id>13         <property name="name" type="java.lang.String">14             <column name="NAME" length="80" />15         </property>16         <property name="price" type="java.lang.Double">17             <column name="PRICE" precision="6" />18         </property>19         <property name="brand" type="java.lang.String">20             <column name="BRAND" length="40" />21         </property>22         <property name="description" type="java.lang.String">23             <column name="DESCRIPTION" length="2000" />24         </property>25     </class>26 </hibernate-mapping>

/compass1/src/com/v512/example/service/ProductManager.java


 1 package com.v512.example.service; 2  3 import java.util.List; 4  5 import com.v512.example.model.Product; 6  7 public interface ProductManager { 8     public void insertProduct(Product p); 9 10     public Product findProdcut(String id);11 12     public List searchProducts(String queryString);13 14 }

/compass1/src/com/v512/example/service/impl/CompassIndexBuilder.java


 1 package com.v512.example.service.impl; 2  3 import org.compass.gps.CompassGps; 4 import org.springframework.beans.factory.InitializingBean; 5  6 /** 7  * 通过quartz定时调度定时重建索引或自动随Spring ApplicationContext启动而重建索引的Builder. 8  * 会启动后延时数秒新开线程调用compassGps.index()函数. 9  * 默认会在Web应用每次启动时重建索引,可以设置buildIndex属性为false来禁止此功能. 也可以不用本Builder,10  * 编写手动调用compassGps.index()的代码.11  * 12  */13 public class CompassIndexBuilder implements InitializingBean {14     // 是否需要建立索引,可被设置为false使本Builder失效.15     private boolean buildIndex = false;16 17     // 索引操作线程延时启动的时间,单位为秒18     private int lazyTime = 10;19 20     // Compass封装21     private CompassGps compassGps;22 23     // 索引线程24     private Thread indexThread = new Thread() {25 26         @Override27         public void run() {28             try {29                 Thread.sleep(lazyTime * 1000);30                 System.out.println("begin compass index...");31                 long beginTime = System.currentTimeMillis();32                 // 重建索引.33 // 如果compass实体中定义的索引文件已存在,索引过程中会建立临时索引,34 // 索引完成后再进行覆盖.35                 compassGps.index();36                 long costTime = System.currentTimeMillis() - beginTime;37                 System.out.println("compss index finished.");38                 System.out.println("costed " + costTime + " milliseconds");39             } catch (InterruptedException e) {40                 e.printStackTrace();41             }42         }43     };44 45     /**46      * 实现<code>InitializingBean</code>接口,在完成注入后调用启动索引线程.47      * 48      * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()49 */50     public void afterPropertiesSet() throws Exception {51         if (buildIndex) {52             indexThread.setDaemon(true);53             indexThread.setName("Compass Indexer");54             indexThread.start();55         }56     }57 58     public void setBuildIndex(boolean buildIndex) {59         this.buildIndex = buildIndex;60     }61 62     public void setLazyTime(int lazyTime) {63         this.lazyTime = lazyTime;64     }65 66     public void setCompassGps(CompassGps compassGps) {67         this.compassGps = compassGps;68     }69 }

/compass1/src/com/v512/example/service/impl/ProductManagerImpl.java


 1 package com.v512.example.service.impl; 2  3 import java.util.ArrayList; 4 import java.util.List; 5  6 import org.compass.core.CompassHits; 7 import org.compass.core.CompassSession; 8 import org.compass.core.CompassTemplate; 9 import org.compass.core.CompassTransaction;10 11 import com.v512.example.dao.ProductDao;12 import com.v512.example.model.Product;13 import com.v512.example.service.ProductManager;14 import org.compass.core.Compass;15 16 public class ProductManagerImpl implements ProductManager {17     private ProductDao productDao;18     private CompassTemplate compassTemplate;19 20     public void setCompassTemplate(CompassTemplate compassTemplate) {21         this.compassTemplate = compassTemplate;22     }23 24     public void setProductDao(ProductDao productDao) {25         this.productDao = productDao;26     }27 28     public Product findProdcut(String id) {29         return productDao.getProduct(id);30     }31 32     public void insertProduct(Product p) {33         productDao.create(p);34 35     }36 37     public List searchProducts(String queryString) {38         Compass compass = compassTemplate.getCompass();39         CompassSession session = compass.openSession();40         List list = new ArrayList();41 42         CompassHits hits = session.queryBuilder().queryString(43                 "name:" + queryString).toQuery().hits();44         System.out.println("queryString:" + queryString);45         System.out.println("hits:" + hits.getLength());46         for (int i = 0; i < hits.length(); i++) {47             Product hit = (Product) hits.data(i);48             list.add(hit);49         }50 51         return list;52     }53 54     public CompassTemplate getCompassTemplate() {55         return compassTemplate;56     }57 58 }

/compass1/src/paoding-dic-home.properties

paoding.dic.home=C:/paoding/dicpaoding.dic.detector.interval=60

/compass1/src/struts.xml


 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4     "http://struts.apache.org/dtds/struts-2.0.dtd"> 5  6 <struts> 7     <constant name="struts.objectFactory" value="spring" /> 8  9     <include file="struts-default.xml" />10 11     <package name="product" extends="struts-default" namespace="/product">12         <!-- 配置Struts2的Action,class值要与applicationContext*.xml中的id的值一致。 -->13         <action name="insert" class="productBean" method="insert">14             <result>insertOk.jsp</result>15         </action>16         <action name="search" class="productBean" method="search">17             <result>searchResults.jsp</result>18         </action>19 20 21     </package>22 23 24 25 26 </struts>

/compass1/WebRoot/product/input.jsp


 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <%@ taglib prefix="s" uri="/struts-tags"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 8 <link href="style/oa.css" rel="stylesheet" type="text/css"> 9 10 <title>添加信息</title>11 </head>12 <body>13 <center>14     <s:form action="insert.action" theme="simple">15     16 <TABLE class="tableEdit" border="0" cellspacing="1" cellpadding="0" style="width:300px;">17     <TBODY>18         <TR>19     <td align="center" class="tdEditTitle">添加商品名称</TD>20         </TR>21         <TR>22             <td>    23 24 25 <table class="tableEdit" style="width:300px;" cellspacing="0" border="0" cellpadding="0">26     <tr>    27     <td class="tdEditLabel" >商品名称</td>                28         <td class="tdEditContent"><s:textfield name="product.name" label="名称" /></td>29     </tr>30     31     <tr>    32     <td class="tdEditLabel" >商品品牌</td>                33         <td class="tdEditContent"><s:textfield name="product.brand" label="品牌" /></td>34     </tr>35     36     <tr>    37     <td class="tdEditLabel" >商品价格</td>                38         <td class="tdEditContent"><s:textfield name="product.price" label="价格" /></td>39     </tr>40     41     <tr>42                 <td class="tdEditLabel" >商品描述</td>    43         <td class="tdEditContent"><s:textarea name="product.description" label="描述" />44         </td>45     </tr>46     <tr>47         <td>&nbsp;48         </td>49         <td><s:submit/>50         <br></td>51     </tr>52 </table>53             </td>54         </TR>55     </TBODY>56 </TABLE>57 </s:form>58 </center>59 </body>60 </html>

/compass1/WebRoot/product/insertOk.jsp


 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body>10 添加商品成功!11 12 </body>13 </html>

/compass1/WebRoot/product/search.jsp


 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3     <%@taglib prefix="s" uri="/struts-tags" %> 4      5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>Insert title here</title>10 </head>11 <body>12 <s:form action="search.action" method="post">13 <s:textfield name="queryString" label="搜索产品"/>14 <s:submit></s:submit>15 </s:form>16 17 18 </body>19 </html>

/compass1/WebRoot/product/searchResults.jsp


 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     import="java.util.List" 3     pageEncoding="UTF-8"%> 4     <%@taglib prefix="s" uri="/struts-tags" %> 5      6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 7 <html> 8 <head> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">10 <title>Insert title here</title>11 </head>12 <body>13 <%14 15 if(((List)request.getAttribute("searchresults")).size()==0){16 %>17     no results found.18 <%} %>19 20 <table border="1">21 <s:iterator value="#request.searchresults">22 <tr><td>23 <s:property value="name"/>24 </td>25 <td>26 27 <s:property value="price"/></td>28 <td>29 30 <s:property value="brand"/></td>31 <td>32 33 <s:property value="description"/></td>34 </tr>35 </s:iterator>36 </table>37 38 </body>39 </html>

/compass1/WebRoot/WEB-INF/applicationContext-compass.xml


 1 <?xml version="1.0" encoding="UTF-8"?> 2  3 <beans xmlns="http://www.springframework.org/schema/beans" 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5     xsi:schemaLocation=" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" 6     default-lazy-init="true"> 7  8  9     <bean id="annotationConfiguration"10         class="org.compass.annotations.config.CompassAnnotationsConfiguration">11     </bean>12 13 14     <bean id="compass" class="org.compass.spring.LocalCompassBean">15         <property name="resourceDirectoryLocations">16             <list>17                 <value>classpath:com/v512</value>18             </list>19         </property>20         <property name="connection">21             <value>/lucene/indexes</value>22         </property>23 24 25         <property name="classMappings">26             <list>27                 <value>com.v512.example.model.Product</value>28             </list>29         </property>30         <property name="compassConfiguration"31             ref="annotationConfiguration" />32 33         <property name="compassSettings">34             <props>35                 <prop key="compass.transaction.factory">36                     org.compass.spring.transaction.SpringSyncTransactionFactory37                 </prop>38                   <prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">net.paoding.analysis.analyzer.PaodingAnalyzer </prop>39             </props>40         </property>41 42         <property name="transactionManager" ref="transactionManager" />43     </bean>44 45 46     <bean id="hibernateGpsDevice"47         class="org.compass.gps.device.hibernate.HibernateGpsDevice">48         <property name="name">49             <value>hibernateDevice</value>50         </property>51         <property name="sessionFactory" ref="sessionFactory" />52         <property name="mirrorDataChanges">53             <value>true</value>54         </property>55     </bean>56     <!-- 同步更新索引 -->57     <bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps"58         init-method="start" destroy-method="stop">59         <property name="compass" ref="compass" />60         <property name="gpsDevices">61             <list>62                 <bean63 class="org.compass.spring.device.SpringSyncTransactionGpsDeviceWrapper">64                     <property name="gpsDevice" ref="hibernateGpsDevice" />65                 </bean>66             </list>67         </property>68     </bean>69 70 71     <bean id="compassTemplate"72         class="org.compass.core.CompassTemplate">73         <property name="compass" ref="compass" />74     </bean>75 76     <!-- 定时重建索引(利用quartz)或随Spring ApplicationContext启动而重建索引 -->77     <bean id="compassIndexBuilder"78         class="com.v512.example.service.impl.CompassIndexBuilder"79         lazy-init="false">80         <property name="compassGps" ref="compassGps" />81         <property name="buildIndex" value="true" />82         <property name="lazyTime" value="10" />83     </bean>84 85 86 87 </beans>

/compass1/WebRoot/WEB-INF/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" 4        xmlns:aop="http://www.springframework.org/schema/aop" 5        xmlns:tx="http://www.springframework.org/schema/tx" 6        xsi:schemaLocation=" 7        http://www.springframework.org/schema/beans 8        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 9        http://www.springframework.org/schema/tx10        http://www.springframework.org/schema/tx/spring-tx-2.5.xsd11        http://www.springframework.org/schema/aop12        http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" default-lazy-init="true">13 14 15     <!-- 定义数据源的Bean ,给Hibernate的sessionFactory-->16     <bean id="dataSource"17         class="org.apache.commons.dbcp.BasicDataSource">18         <property name="driverClassName"19             value="oracle.jdbc.driver.OracleDriver">20         </property>21         <property name="url"22             value="jdbc:oracle:thin:@192.168.1.3:1521:ora9">23         </property>24         <property name="username" value="scott"></property>25         <property name="password" value="tiger"></property>26     </bean>27     28 <!-- 定义Hibernate的sessionFactory,通过该Bean,可以获得Hibernate的Session-->29     <bean id="sessionFactory"30         class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">31         <property name="dataSource">32             <ref bean="dataSource" />33         </property>34         <property name="hibernateProperties">35             <props>36                 <prop key="hibernate.dialect">37                     org.hibernate.dialect.Oracle9Dialect38                 </prop>39                 <!--设置二级缓冲-->40                 <prop key="hibernate.cache.provider_class">41                     org.hibernate.cache.EhCacheProvider42                 </prop>43                 <!--设置二级缓冲,打开查询缓冲-->44                 <prop key="hibernate.cache.use_query_cache">true</prop>45                 <!--设置显示Hibernate操作的SQL语句-->46                 <prop key="hibernate.show_sql">true</prop>47             </props>48         </property>49         <property name="mappingResources">50             <list>                51                 <value>52                     com/v512/example/model/Product.hbm.xml53                 </value>54             </list>55         </property>56     </bean>57 58     <bean id="productDao" class="com.v512.example.dao.hibernate.ProductDaoHibernate">59     <property name="sessionFactory" ref="sessionFactory"></property>60     </bean>61     <bean id="productManager" class="com.v512.example.service.impl.ProductManagerImpl">62     <property name="productDao" ref="productDao"></property>63     <property name="compassTemplate" ref="compassTemplate"></property>64     </bean>65     66     <bean id="productBean" class="com.v512.example.action.ProductAction" scope="prototype">67     <property name="productManager" ref="productManager"></property>68     69     </bean>70     71     72         <!-- 配置事务管理器 -->    73     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">74         <property name="sessionFactory">75             <ref local="sessionFactory"/>76         </property>77     </bean>78     79     <!-- 配置事务特性 ,配置add、delete和update开始的方法,事务传播特性为required-->       80     <tx:advice id="txAdvice" transaction-manager="transactionManager">81         <tx:attributes>82             <tx:method name="insert*" propagation="REQUIRED"/>83             <tx:method name="delete*" propagation="REQUIRED"/>84             <tx:method name="update*" propagation="REQUIRED"/>85             <tx:method name="*" read-only="true"/>86         </tx:attributes>87     </tx:advice>88     89     <!-- 配置那些类的方法进行事务管理,当前cn.com.jobedu.oa.service包中的子包、类中所有方法需要,还需要参考tx:advice的设置 -->90     <aop:config>91         <aop:pointcut id="allManagerMethod" expression="execution (* com.v512.example.service.*.*(..))"/>92         <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/>93     </aop:config>        94     95     96     </beans>

/compass1/WebRoot/WEB-INF/web.xml


 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5"  3     xmlns="http://java.sun.com/xml/ns/javaee"  4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7      8     <!--定义Spring的配置的位置,可以定义多个配置文件,可以使用通配符。  --> 9     <context-param>10         <param-name>contextConfigLocation</param-name>11         <param-value>/WEB-INF/applicationContext*.xml</param-value>12     </context-param>13     <!--设置一起动当前的Web应用,就加载Spring,让Spring管理Bean-->14     <listener>15         <listener-class>16             org.springframework.web.context.ContextLoaderListener17         </listener-class>18     </listener>19         <!--解决Hibernate延迟加载出现的问题,需要放到struts2过滤器之前-->20     <filter>21         <filter-name>lazyLoadingFilter</filter-name>22         <filter-class>23             org.springframework.orm.hibernate3.support.OpenSessionInViewFilter24         </filter-class>25     </filter>26     27         <!--Struts2的过滤器,使用Struts2,必须配置该项-->28     <filter>29         <filter-name>struts2</filter-name>30         <filter-class>31             org.apache.struts2.dispatcher.FilterDispatcher32         </filter-class>33     </filter>    34     35     36         <!--解决Hibernate延迟加载出现的问题,仍需要放到struts2过滤器mapping之前-->37 <filter-mapping>38         <filter-name>lazyLoadingFilter</filter-name>39         <url-pattern>*.action</url-pattern>40     </filter-mapping>41 <!--Struts2的过滤器,配套的filter-mapping-->42     <filter-mapping>43         <filter-name>struts2</filter-name>44         <url-pattern>/*</url-pattern>45     </filter-mapping>46 52   <welcome-file-list>53     <welcome-file>index.jsp</welcome-file>54   </welcome-file-list>55 </web-app>