ITeye博客

Compass技术文档

a52071453 · 2012-06-24 15:15 · compass · Web前端 · Java · Lucene · Spring · Hibernate · compass · Markdown

目录

一、原理描述:...

二、术语解释:...

三、下载地址:...

四、使用流程:  …………………………………………………………………………………….

五、基于SSH的compass的实例: …………………………………………………………………

 

 

一、原理描述:

       Compass是一流的开放源码JAVA搜索引擎框架,对于你的应用修饰,搜索引擎语义更具有能力。依靠顶级的Lucene搜索引擎,Compass 结合了,像 Hibernate和 Spring的流行的框架,为你的应用提供了从数据模型和数据源同步改变的搜索力.并且添加了2方面的特征,事物管理和快速更新优化.
    Compass的目标是:把java应用简单集成到搜索引擎中.编码更少,查找数据更便捷 .

二、术语解释:

名称

描述

Lucene

  Apache Lucene是一个基于Java全文搜索引擎,利用它可以轻易地为Java软件加入全文搜寻功能。Lucene的最主要工作是替文件的每一个字作索引,索引让搜寻的效率比传统的逐字比较大大提高了,Lucene提供一组解读,过滤,分析文件,编排和使用索引的提供一组解读,过滤,分析文件,编排和使用索引的API,它的强大之处除了高效和简单外,是最重要的是使使用都是可以随时应自己需要自订其功能。开发者可以把Lucene看成一个支持全文索引的数据库系统的.

Compass

我对Compass的定义是面向域模型的搜索框架, 面向域模型意味着必须支持对对象的搜索,对持久化对象的搜索,和对XML文档对象的搜索,同时还必须支持事务的处理,包括对创建,更新,保存,删除进行事务级别的处理. 所以, Compass是基于Lucene, 高于Lucene的. 有个形象的比喻. Compass对于Lucene就像Hibernate对于JDBC,太有才了!Compass的开发路数完全参照Hibernate.

OSEM

对象搜索引擎影射(Object Search Engine Mapping),通过xml配置文件,提供了POJO's (Plain Old Java Objects)到搜索引擎.

三、下载地址:

软件名称

下载地址

软件描述

Compass框架、jar包

http://www.compassframework.org/

基于Java的搜索引擎

四、使用流程:

网络机器人程序

www文档

 

网络机器人程序

 

建立索引

从数据库中搜索信息

Tomcat服务器

JSP

索引数据库

浏览器

浏览器

五、基于SSH的compass的实例:

      step1
在ssh2的基础上开发  加入jar包(compass-2.1.2.jar compass-index-patch.jar
lucene-analyzers-2.4.0.jar lucene-core-2.4.0.jar lucene-highlighter-2.4.0.jar  paoding-analysis.jar
)
step2
先来看下实体bean的编写

Java代码

  1. package com.v512.example.model;
  2. import org.compass.annotations.*;
  3. /**
  4. * Product entity.
  5. *
  6. * @author MyEclipse Persistence Tools
  7. */
  8. @Searchable
  9. public class Product implements java.io.Serializable {
  10. // Fields
  11. @SearchableId
  12. private String id;
  13. @SearchableProperty(name="name",index=Index.ANALYZED,store=Store.YES)
  14. private String name;
  15. @SearchableProperty(name="price",index=Index.NOT_ANALYZED,store=Store.YES)
  16. private Double price;
  17. @SearchableProperty(name="brand",index=Index.ANALYZED,store=Store.YES)
  18. private String brand;
  19. @SearchableProperty(name="description",index=Index.ANALYZED,store=Store.YES)
  20. private String description;
  21. // Constructors
  22. /** default constructor */
  23. public Product() {
  24. }
  25. /** full constructor */
  26. public Product(String name, Double price, String brand, String description) {
  27. this.name = name;
  28. this.price = price;
  29. this.brand = brand;
  30. this.description = description;
  31. }
  32. // Property accessors
  33. public String getId() {
  34. return this.id;
  35. }
  36. public void setId(String id) {
  37. this.id = id;
  38. }
  39. public String getName() {
  40. return this.name;
  41. }
  42. public void setName(String name) {
  43. this.name = name;
  44. }
  45. public Double getPrice() {
  46. return this.price;
  47. }
  48. public void setPrice(Double price) {
  49. this.price = price;
  50. }
  51. public String getBrand() {
  52. return this.brand;
  53. }
  54. public void setBrand(String brand) {
  55. this.brand = brand;
  56. }
  57. public String getDescription() {
  58. return this.description;
  59. }
  60. public void setDescription(String description) {
  61. this.description = description;
  62. }
  63. }

package com.v512.example.model;

import org.compass.annotations.*;

/**

 * Product entity.

 *

 * @author MyEclipse Persistence Tools

 */

@Searchable

public class Product implements java.io.Serializable {

 

  // Fields

 

  @SearchableId

  private String id;

  @SearchableProperty(name="name",index=Index.ANALYZED,store=Store.YES)

  private String name;

  @SearchableProperty(name="price",index=Index.NOT_ANALYZED,store=Store.YES)

  private Double price;

  @SearchableProperty(name="brand",index=Index.ANALYZED,store=Store.YES)

  private String brand;

  @SearchableProperty(name="description",index=Index.ANALYZED,store=Store.YES)

  private String description;

 

  // Constructors

 

  /** default constructor */

  public Product() {

  }

 

  /** full constructor */

  public Product(String name, Double price, String brand, String description) {

   this.name = name;

   this.price = price;

   this.brand = brand;

   this.description = description;

  }

 

  // Property accessors

 

  public String getId() {

   return this.id;

  }

 

  public void setId(String id) {

   this.id = id;

  }

 

  public String getName() {

   return this.name;

  }

 

  public void setName(String name) {

   this.name = name;

  }

 

  public Double getPrice() {

   return this.price;

  }

 

  public void setPrice(Double price) {

   this.price = price;

  }

 

  public String getBrand() {

   return this.brand;

  }

 

  public void setBrand(String brand) {

   this.brand = brand;

  }

 

  public String getDescription() {

   return this.description;

  }

 

  public void setDescription(String description) {

   this.description = description;

  }

 

}

step3属性文件Product.hbm.xml

Java代码

  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" >
  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>

<?xml version="1.0" encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--

    Mapping file autogenerated by MyEclipse Persistence Tools

-->

<hibernate-mapping>

    <class name="com.v512.example.model.Product" table="PRODUCT" >

        <id name="id" type="java.lang.String">

            <column name="ID" length="40" />

            <generator class="uuid.hex" />

        </id>

        <property name="name" type="java.lang.String">

            <column name="NAME" length="80" />

        </property>

        <property name="price" type="java.lang.Double">

            <column name="PRICE" precision="6" />

        </property>

        <property name="brand" type="java.lang.String">

            <column name="BRAND" length="40" />

        </property>

        <property name="description" type="java.lang.String">

            <column name="DESCRIPTION" length="2000" />

        </property>

    </class>

</hibernate-mapping>

要使用Compass必须加入一个applicationContext-compass.xml文件,文件名可以自行定义这个就不用说了 废话

step4applicationContext-compass.xml:

Java代码

  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. xsi:schemaLocation=" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
  5. default-lazy-init="true">
  6. <!-- 配置compass的注解功能 -->
  7. <bean id="annotationConfiguration"
  8. class="org.compass.annotations.config.CompassAnnotationsConfiguration">
  9. </bean>
  10. <bean id="compass" class="org.compass.spring.LocalCompassBean">
  11. <!-- 配置需要索引的实体映射文件的路径 -->
  12. <property name="resourceDirectoryLocations">
  13. <list>
  14. <value>classpath:com/v512/example/model</value>
  15. </list>
  16. </property>
  17. <!-- 设置存放索引的路径 -->
  18. <property name="connection">
  19. <value>/lucene/indexes</value>
  20. </property>
  21. <!--配置要搜索的类,作用:会根据以下的类建立索引  -->
  22. <property name="classMappings">
  23. <list>
  24. <value>com.v512.example.model.Product</value>
  25. </list>
  26. </property>
  27. <property name="compassConfiguration"
  28. ref="annotationConfiguration" />
  29. <!--compass的一些属性设置  -->
  30. <property name="compassSettings">
  31. <props>
  32. <prop key="compass.transaction.factory">
  33. org.compass.spring.transaction.SpringSyncTransactionFactory
  34. </prop>
  35. <prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">net.paoding.analysis.analyzer.PaodingAnalyzer </prop>
  36. </props>
  37. </property>
  38. <!--compass的事务管理器  -->
  39. <property name="transactionManager" ref="transactionManager" />
  40. </bean>
  41. <bean id="hibernateGpsDevice"
  42. class="org.compass.gps.device.hibernate.HibernateGpsDevice">
  43. <property name="name">
  44. <value>hibernateDevice</value>
  45. </property>
  46. <property name="sessionFactory" ref="sessionFactory" />
  47. <property name="mirrorDataChanges">
  48. <value>true</value>
  49. </property>
  50. </bean>
  51. <!-- 同步更新索引 -->
  52. <bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps"
  53. init-method="start" destroy-method="stop">
  54. <property name="compass" ref="compass" />
  55. <property name="gpsDevices">
  56. <list>
  57. <bean
  58. class="org.compass.spring.device.SpringSyncTransactionGpsDeviceWrapper">
  59. <property name="gpsDevice" ref="hibernateGpsDevice" />
  60. </bean>
  61. </list>
  62. </property>
  63. </bean>
  64. <bean id="compassTemplate"
  65. class="org.compass.core.CompassTemplate">
  66. <property name="compass" ref="compass" />
  67. </bean>
  68. <!-- 定时重建索引(利用quartz)或随Spring ApplicationContext启动而重建索引 -->
  69. <bean id="compassIndexBuilder"
  70. class="com.v512.example.service.impl.CompassIndexBuilder"
  71. lazy-init="false">
  72. <property name="compassGps" ref="compassGps" />
  73. <property name="buildIndex" value="true" />
  74. <property name="lazyTime" value="10" />
  75. </bean>
  76. </beans>

<?xml version="1.0" encoding="UTF-8"?>

 

<beans xmlns="http://www.springframework.org/schema/beans"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation=" http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"

  default-lazy-init="true">

 

    <!-- 配置compass的注解功能 -->

  <bean id="annotationConfiguration"

   class="org.compass.annotations.config.CompassAnnotationsConfiguration">

  </bean>

 

 

  <bean id="compass" class="org.compass.spring.LocalCompassBean">

      <!-- 配置需要索引的实体映射文件的路径 -->

   <property name="resourceDirectoryLocations">

     <list>

      <value>classpath:com/v512/example/model</value>

     </list>

   </property>

    <!-- 设置存放索引的路径 -->

   <property name="connection">

     <value>/lucene/indexes</value>

   </property>

  

       <!--配置要搜索的类,作用:会根据以下的类建立索引  -->

   <property name="classMappings">

     <list>

      <value>com.v512.example.model.Product</value>

     </list>

   </property>

   <property name="compassConfiguration"

     ref="annotationConfiguration" />

 

        <!--compass的一些属性设置  -->

   <property name="compassSettings">

     <props>

      <prop key="compass.transaction.factory">

        org.compass.spring.transaction.SpringSyncTransactionFactory

      </prop>

        <prop key="compass.engine.analyzer.MMAnalyzer.CustomAnalyzer">net.paoding.analysis.analyzer.PaodingAnalyzer </prop>

     </props>

   </property>

        <!--compass的事务管理器  -->

   <property name="transactionManager" ref="transactionManager" />

  </bean>

 

 

  <bean id="hibernateGpsDevice"

   class="org.compass.gps.device.hibernate.HibernateGpsDevice">

   <property name="name">

     <value>hibernateDevice</value>

   </property>

   <property name="sessionFactory" ref="sessionFactory" />

   <property name="mirrorDataChanges">

     <value>true</value>

   </property>

  </bean>

  <!-- 同步更新索引 -->

  <bean id="compassGps" class="org.compass.gps.impl.SingleCompassGps"

   init-method="start" destroy-method="stop">

   <property name="compass" ref="compass" />

   <property name="gpsDevices">

     <list>

      <bean

        class="org.compass.spring.device.SpringSyncTransactionGpsDeviceWrapper">

        <property name="gpsDevice" ref="hibernateGpsDevice" />

      </bean>

     </list>

   </property>

  </bean>

 

 

  <bean id="compassTemplate"

   class="org.compass.core.CompassTemplate">

   <property name="compass" ref="compass" />

  </bean>

 

  <!-- 定时重建索引(利用quartz)或随Spring ApplicationContext启动而重建索引 -->

  <bean id="compassIndexBuilder"

   class="com.v512.example.service.impl.CompassIndexBuilder"

   lazy-init="false">

   <property name="compassGps" ref="compassGps" />

   <property name="buildIndex" value="true" />

   <property name="lazyTime" value="10" />

  </bean>

 

 

 

</beans>

中间都有注解  就不多解释了

下面来编写dao及dao的实现以及severce层

step5

Java代码

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

package com.v512.example.dao;

 

import java.util.List;

 

import com.v512.example.model.Product;

 

public interface ProductDao {

  public void create(Product p);

  public Product getProduct(String id);

  public List getProducts();

  public void update(Product product);

  public void remove(String id);

 

}

 

Java代码

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

package com.v512.example.dao.hibernate;

 

import java.util.List;

 

import com.v512.example.dao.ProductDao;

import com.v512.example.model.Product;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ProductDaoHibernate extends HibernateDaoSupport implements ProductDao {

 

  public void create(Product p) {

   getHibernateTemplate().save(p);

 

  }

 

  public Product getProduct(String id) {

   return (Product)getHibernateTemplate().get(Product.class, id);

  }

 

  public List getProducts() {

     return getHibernateTemplate().find("from Product order by id desc");

  }

 

  public void remove(String id) {

  getHibernateTemplate().delete(getProduct(id));

 

  }

 

  public void update(Product product) {

   getHibernateTemplate().saveOrUpdate(product);

 

  }

 

}

 

servece

Java代码

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

package com.v512.example.service;

 

import java.util.List;

 

import com.v512.example.model.Product;

 

public interface ProductManager {

  public void insertProduct(Product p);

  public Product findProdcut(String id);

  public List searchProducts(String queryString);

 

 

}

servece的实现

Java代码

  1. package com.v512.example.service.impl;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.compass.core.CompassHits;
  5. import org.compass.core.CompassSession;
  6. import org.compass.core.CompassTemplate;
  7. import org.compass.core.CompassTransaction;
  8. import com.v512.example.dao.ProductDao;
  9. import com.v512.example.model.Product;
  10. import com.v512.example.service.ProductManager;
  11. import org.compass.core.Compass;
  12. public class ProductManagerImpl implements ProductManager {
  13. private ProductDao productDao;
  14. private CompassTemplate compassTemplate;
  15. public void setCompassTemplate(CompassTemplate compassTemplate){
  16. this.compassTemplate=compassTemplate;
  17. }
  18. public void setProductDao(ProductDao productDao){
  19. this.productDao=productDao;
  20. }
  21. public Product findProdcut(String id) {
  22. return productDao.getProduct(id);
  23. }
  24. public void insertProduct(Product p) {
  25. productDao.create(p);
  26. }
  27. public List searchProducts(String queryString) {
  28. Compass compass = compassTemplate.getCompass();
  29. CompassSession session=compass.openSession();
  30. List list = new ArrayList();
  31. //这里不需要开启事务了,因为在调用这个方法之前就已经开启了事务
  32. CompassHits hits= session.queryBuilder().queryString("name:"+queryString).toQuery().hits();
  33. System.out.println("queryString:"+queryString);
  34. System.out.println("hits:"+hits.getLength());
  35. for(int i=0;i<hits.length();i++){
  36. Product hit=(Product)hits.data(i);
  37. list.add(hit);
  38. }
  39. return list;
  40. }
  41. public CompassTemplate getCompassTemplate() {
  42. return compassTemplate;
  43. }
  44. }

package com.v512.example.service.impl;

 

import java.util.ArrayList;

import java.util.List;

 

import org.compass.core.CompassHits;

import org.compass.core.CompassSession;

import org.compass.core.CompassTemplate;

import org.compass.core.CompassTransaction;

 

import com.v512.example.dao.ProductDao;

import com.v512.example.model.Product;

import com.v512.example.service.ProductManager;

import org.compass.core.Compass;

public class ProductManagerImpl implements ProductManager {

  private ProductDao productDao;

  private CompassTemplate compassTemplate;

 

 

 

 

  public void setCompassTemplate(CompassTemplate compassTemplate){

   this.compassTemplate=compassTemplate;

  }

 

  public void setProductDao(ProductDao productDao){

   this.productDao=productDao;

  }

 

  public Product findProdcut(String id) {

   return productDao.getProduct(id);  

  }

 

  public void insertProduct(Product p) {

  productDao.create(p);

  }

 

  public List searchProducts(String queryString) {

   Compass compass = compassTemplate.getCompass();

   CompassSession session=compass.openSession();

   List list = new ArrayList();

   //这里不需要开启事务了,因为在调用这个方法之前就已经开启了事务

   CompassHits hits= session.queryBuilder().queryString("name:"+queryString).toQuery().hits();

   System.out.println("queryString:"+queryString);

   System.out.println("hits:"+hits.getLength());

   for(int i=0;i<hits.length();i++){

     Product hit=(Product)hits.data(i);

     list.add(hit);

   }

  

   return list;

  }

 

 

 

  public CompassTemplate getCompassTemplate() {

   return compassTemplate;

  }

 

}

所有的都做完了
现在编写jsp页面

step6
insertProduct.jsp

Java代码

  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. <title>添加信息</title>
  10. </head>
  11. <body>
  12. <center>
  13. <s:form action="insert.action" theme="simple">
  14. <TABLE class="tableEdit" border="0" cellspacing="1" cellpadding="0" style="width:300px;">
  15. <TBODY>
  16. <TR>
  17. <td align="center" class="tdEditTitle">添加商品名称</TD>
  18. </TR>
  19. <TR>
  20. <td>
  21. <table class="tableEdit" style="width:300px;" cellspacing="0" border="0" cellpadding="0">
  22. <tr>
  23. <td class="tdEditLabel" >商品名称</td>
  24. <td class="tdEditContent"><s:textfield name="product.name" label="名称" /></td>
  25. </tr>
  26. <tr>
  27. <td class="tdEditLabel" >商品品牌</td>
  28. <td class="tdEditContent"><s:textfield name="product.brand" label="品牌" /></td>
  29. </tr>
  30. <tr>
  31. <td class="tdEditLabel" >商品价格</td>
  32. <td class="tdEditContent"><s:textfield name="product.price" label="价格" /></td>
  33. </tr>
  34. <tr>
  35. <td class="tdEditLabel" >商品描述</td>
  36. <td class="tdEditContent"><s:textarea name="product.description" label="描述" />
  37. </td>
  38. </tr>
  39. <tr>
  40. <td> 
  41. </td>
  42. <td><s:submit/>
  43. <br></td>
  44. </tr>
  45. </table>
  46. </td>
  47. </TR>
  48. </TBODY>
  49. </TABLE>
  50. </s:form>
  51. </center>
  52. </body>
  53. </html>

<%@ page language="java" contentType="text/html; charset=UTF-8"

  pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<link href="style/oa.css" rel="stylesheet" type="text/css">

 

<title>添加信息</title>

</head>

<body>

<center>

  <s:form action="insert.action" theme="simple">

 

<TABLE class="tableEdit" border="0" cellspacing="1" cellpadding="0" style="width:300px;">

  <TBODY>

   <TR>

  <td align="center" class="tdEditTitle">添加商品名称</TD>

   </TR>

   <TR>

     <td> 

 

 

<table class="tableEdit" style="width:300px;" cellspacing="0" border="0" cellpadding="0">

  <tr> 

  <td class="tdEditLabel" >商品名称</td>     

   <td class="tdEditContent"><s:textfield name="product.name" label="名称" /></td>

  </tr>

 

  <tr> 

  <td class="tdEditLabel" >商品品牌</td>     

   <td class="tdEditContent"><s:textfield name="product.brand" label="品牌" /></td>

  </tr>

 

  <tr> 

  <td class="tdEditLabel" >商品价格</td>     

   <td class="tdEditContent"><s:textfield name="product.price" label="价格" /></td>

  </tr>

 

  <tr>

      <td class="tdEditLabel" >商品描述</td> 

   <td class="tdEditContent"><s:textarea name="product.description" label="描述" />

   </td>

  </tr>

  <tr>

   <td> 

   </td>

   <td><s:submit/>

   <br></td>

  </tr>

</table>

     </td>

   </TR>

  </TBODY>

</TABLE>

</s:form>

</center>

</body>

</html>

step7

编写action

Java代码

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

package com.v512.example.action;

 

import java.util.List;

 

import com.opensymphony.xwork2.ActionSupport;

import com.v512.example.model.Product;

import com.v512.example.service.ProductManager;

import org.apache.struts2.ServletActionContext;

 

public class ProductAction extends ActionSupport {

 

  private static final long serialVersionUID = 3795048906805728732L;

  private ProductManager productManager;

  private Product product;

  private String queryString;

 

  public void setQueryString(String queryString){

   this.queryString=queryString;

  }

 

  public Product getProduct() {

   return product;

  }

 

  public void setProduct(Product product) {

   this.product = product;

  }

 

  public void setProductManager(ProductManager productManager){

   this.productManager=productManager;

  }

 

  public String insert(){

   productManager.insertProduct(product);

   return SUCCESS;

  }

  public String search(){

   List results=productManager.searchProducts(queryString);

   System.out.println(results.size());

   ServletActionContext.getRequest().setAttribute("searchresults", results);

   return SUCCESS;

  }

 

 

}

step8关于Struts2的配置文件如下

Java代码

  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. <struts>
  6. <constant name="struts.objectFactory" value="spring" />
  7. <include file="struts-default.xml"/>
  8. <package name="product" extends="struts-default"
  9. namespace="/product">
  10. <!-- 配置Struts2的Action,class值要与applicationContext*.xml中的id的值一致。 -->
  11. <action name="insert"
  12. class="productBean" method="insert">
  13. <result >insertOk.jsp</result>
  14. </action>
  15. <action name="search"
  16. class="productBean" method="search">
  17. <result >searchResults.jsp</result>
  18. </action>
  19. </package>
  20. </struts>

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    "http://struts.apache.org/dtds/struts-2.0.dtd">

 

<struts>

  <constant name="struts.objectFactory" value="spring" />

 

  <include file="struts-default.xml"/>

     

    <package name="product" extends="struts-default"

   namespace="/product">

  

   <!-- 配置Struts2的Action,class值要与applicationContext*.xml中的id的值一致。 -->

   <action name="insert"

     class="productBean" method="insert">

     <result >insertOk.jsp</result>

   </action>  

   <action name="search"

     class="productBean" method="search">

     <result >searchResults.jsp</result>

   </action>

  

     </package>

 

</struts>

 

如果插入成功就跳转到insertOk。jsp

Java代码

  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. </body>
  12. </html>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

添加商品成功!

 

</body>

</html>

step9到此所有准备工作都做完了
下面来看下 spring的配置文件applicationContext.xml 和web.xml
web.xml

Java代码

  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. <!--定义Spring的配置的位置,可以定义多个配置文件,可以使用通配符。  -->
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>/WEB-INF/applicationContext*.xml</param-value>
  11. </context-param>
  12. <!--设置一起动当前的Web应用,就加载Spring,让Spring管理Bean-->
  13. <listener>
  14. <listener-class>
  15. org.springframework.web.context.ContextLoaderListener
  16. </listener-class>
  17. </listener>
  18. <!--解决Hibernate延迟加载出现的问题,需要放到struts2过滤器之前-->
  19. <filter>
  20. <filter-name>lazyLoadingFilter</filter-name>
  21. <filter-class>
  22. org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
  23. </filter-class>
  24. </filter>
  25. <!--Struts2的过滤器,使用Struts2,必须配置该项-->
  26. <filter>
  27. <filter-name>struts2</filter-name>
  28. <filter-class>
  29. org.apache.struts2.dispatcher.FilterDispatcher
  30. </filter-class>
  31. </filter>
  32. <!--解决Hibernate延迟加载出现的问题,仍需要放到struts2过滤器mapping之前-->
  33. <filter-mapping>
  34. <filter-name>lazyLoadingFilter</filter-name>
  35. <url-pattern>*.action</url-pattern>
  36. </filter-mapping>
  37. <!--Struts2的过滤器,配套的filter-mapping-->
  38. <filter-mapping>
  39. <filter-name>struts2</filter-name>
  40. <url-pattern>/*</url-pattern>
  41. </filter-mapping>
  42. <welcome-file-list>
  43. <welcome-file>index.jsp</welcome-file>
  44. </welcome-file-list>
  45. </web-app>

<?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">

 

  <!--定义Spring的配置的位置,可以定义多个配置文件,可以使用通配符。  -->

  <context-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>/WEB-INF/applicationContext*.xml</param-value>

  </context-param>

  <!--设置一起动当前的Web应用,就加载Spring,让Spring管理Bean-->

  <listener>

   <listener-class>

     org.springframework.web.context.ContextLoaderListener

   </listener-class>

  </listener>

   <!--解决Hibernate延迟加载出现的问题,需要放到struts2过滤器之前-->

  <filter>

   <filter-name>lazyLoadingFilter</filter-name>

   <filter-class>

     org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

   </filter-class>

  </filter>

 

   <!--Struts2的过滤器,使用Struts2,必须配置该项-->

  <filter>

   <filter-name>struts2</filter-name>

   <filter-class>

     org.apache.struts2.dispatcher.FilterDispatcher

   </filter-class>

  </filter> 

 

 

   <!--解决Hibernate延迟加载出现的问题,仍需要放到struts2过滤器mapping之前-->

<filter-mapping>

   <filter-name>lazyLoadingFilter</filter-name>

   <url-pattern>*.action</url-pattern>

  </filter-mapping>

<!--Struts2的过滤器,配套的filter-mapping-->

  <filter-mapping>

   <filter-name>struts2</filter-name>

   <url-pattern>/*</url-pattern>

  </filter-mapping> 

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>

applicationContext.xml

Java代码

  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/tx
  10. http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" default-lazy-init="true">
  13. <!-- mysql数据库 :定义数据源的Bean ,给Hibernate的sessionFactory -->
  14. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  15. <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
  16. <property name="url" value="jdbc:mysql://localhost:3306/ssh2compass?useUnicode=true&characterEncoding=UTF-8"/>
  17. <property name="username" value="root"/>
  18. <property name="password" value="123456"/>
  19. <!-- 连接池启动时的初始值 -->
  20. <property name="initialSize" value="1"/>
  21. <!-- 连接池的最大值 -->
  22. <property name="maxActive" value="500"/>
  23. <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
  24. <property name="maxIdle" value="2"/>
  25. <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
  26. <property name="minIdle" value="1"/>
  27. </bean>
  28. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  29. <property name="dataSource" ref="dataSource"/>
  30. <property name="mappingResources">
  31. <list>
  32. <value>com/v512/example/model/Product.hbm.xml</value>
  33. </list>
  34. </property>
  35. <property name="hibernateProperties">
  36. <value>
  37. hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
  38. hibernate.hbm2ddl.auto=update
  39. hibernate.show_sql=false
  40. hibernate.format_sql=false
  41. hibernate.cache.use_second_level_cache=true
  42. hibernate.cache.use_query_cache=false
  43. hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
  44. </value>
  45. </property>
  46. </bean>
  47. <!-- oracle数据库 :定义数据源的Bean ,给Hibernate的sessionFactory-->
  48. <!--
  49. <bean id="dataSource"
  50. class="org.apache.commons.dbcp.BasicDataSource">
  51. <property name="driverClassName"
  52. value="oracle.jdbc.driver.OracleDriver">
  53. </property>
  54. <property name="url"
  55. value="jdbc:oracle:thin:@192.168.1.3:1521:ora9">
  56. </property>
  57. <property name="username" value="scott"></property>
  58. <property name="password" value="tiger"></property>
  59. </bean>
  60. -->
  61. <!-- 定义Hibernate的sessionFactory,通过该Bean,可以获得Hibernate的Session-->
  62. <!--
  63. <bean id="sessionFactory"
  64. class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  65. <property name="dataSource">
  66. <ref bean="dataSource" />
  67. </property>
  68. <property name="hibernateProperties">
  69. <props>
  70. <prop key="hibernate.dialect">
  71. org.hibernate.dialect.Oracle9Dialect
  72. </prop>
  73. <prop key="hibernate.cache.provider_class">
  74. org.hibernate.cache.EhCacheProvider
  75. </prop>
  76. <prop key="hibernate.cache.use_query_cache">true</prop>
  77. <prop key="hibernate.show_sql">true</prop>
  78. </props>
  79. </property>
  80. <property name="mappingResources">
  81. <list>
  82. <value>
  83. com/v512/example/model/Product.hbm.xml
  84. </value>
  85. </list>
  86. </property>
  87. </bean>
  88. -->
  89. <bean id="productDao" class="com.v512.example.dao.hibernate.ProductDaoHibernate">
  90. <property name="sessionFactory" ref="sessionFactory"></property>
  91. </bean>
  92. <bean id="productManager" class="com.v512.example.service.impl.ProductManagerImpl">
  93. <property name="productDao" ref="productDao"></property>
  94. <property name="compassTemplate" ref="compassTemplate"></property>
  95. </bean>
  96. <bean id="productBean" class="com.v512.example.action.ProductAction" scope="prototype">
  97. <property name="productManager" ref="productManager"></property>
  98. </bean>
  99. <!-- 配置事务管理器 -->
  100. <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  101. <property name="sessionFactory">
  102. <ref local="sessionFactory"/>
  103. </property>
  104. </bean>
  105. <!-- 配置事务特性 ,配置add、delete和update开始的方法,事务传播特性为required-->
  106. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  107. <tx:attributes>
  108. <tx:method name="insert*" propagation="REQUIRED"/>
  109. <tx:method name="delete*" propagation="REQUIRED"/>
  110. <tx:method name="update*" propagation="REQUIRED"/>
  111. <tx:method name="*" read-only="true"/>
  112. </tx:attributes>
  113. </tx:advice>
  114. <!-- 配置那些类的方法进行事务管理,当前cn.com.jobedu.oa.service包中的子包、类中所有方法需要,还需要参考tx:advice的设置 -->
  115. <aop:config>
  116. <aop:pointcut id="allManagerMethod" expression="execution (* com.v512.example.service.*.*(..))"/>
  117. <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/>
  118. </aop:config>
  119. </beans>

<?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:aop="http://www.springframework.org/schema/aop"

       xmlns:tx="http://www.springframework.org/schema/tx"

       xsi:schemaLocation="

       http://www.springframework.org/schema/beans

       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

       http://www.springframework.org/schema/tx

       http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

       http://www.springframework.org/schema/aop

       http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" default-lazy-init="true">

 

     

 

   

  <!-- mysql数据库 :定义数据源的Bean ,给Hibernate的sessionFactory -->

  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">

      <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>

      <property name="url" value="jdbc:mysql://localhost:3306/ssh2compass?useUnicode=true&characterEncoding=UTF-8"/>

      <property name="username" value="root"/>

      <property name="password" value="123456"/>

       <!-- 连接池启动时的初始值 -->

    <property name="initialSize" value="1"/>

    <!-- 连接池的最大值 -->

    <property name="maxActive" value="500"/>

    <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

    <property name="maxIdle" value="2"/>

    <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->

    <property name="minIdle" value="1"/>

    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

       <property name="dataSource" ref="dataSource"/>

    <property name="mappingResources">

       <list>

         <value>com/v512/example/model/Product.hbm.xml</value>

       </list>

    </property>

       <property name="hibernateProperties">

       <value>

           hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

           hibernate.hbm2ddl.auto=update

           hibernate.show_sql=false

            hibernate.format_sql=false

           hibernate.cache.use_second_level_cache=true

                 hibernate.cache.use_query_cache=false

              hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider

         </value>

       </property>

  </bean>

 

  <!-- oracle数据库 :定义数据源的Bean ,给Hibernate的sessionFactory-->

  <!--

  <bean id="dataSource"

   class="org.apache.commons.dbcp.BasicDataSource">

   <property name="driverClassName"

     value="oracle.jdbc.driver.OracleDriver">

   </property>

   <property name="url"

     value="jdbc:oracle:thin:@192.168.1.3:1521:ora9">

   </property>

   <property name="username" value="scott"></property>

   <property name="password" value="tiger"></property>

  </bean>

    -->

   

<!-- 定义Hibernate的sessionFactory,通过该Bean,可以获得Hibernate的Session-->

  <!--

  <bean id="sessionFactory"

   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

   <property name="dataSource">

     <ref bean="dataSource" />

   </property>

   <property name="hibernateProperties">

     <props>

      <prop key="hibernate.dialect">

        org.hibernate.dialect.Oracle9Dialect

      </prop>

      <prop key="hibernate.cache.provider_class">

        org.hibernate.cache.EhCacheProvider

      </prop>

      <prop key="hibernate.cache.use_query_cache">true</prop>

      <prop key="hibernate.show_sql">true</prop>

     </props>

   </property>

   <property name="mappingResources">

     <list>     

      <value>

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

      </value>

     </list>

   </property>

  </bean>

   -->

 

  <bean id="productDao" class="com.v512.example.dao.hibernate.ProductDaoHibernate">

  <property name="sessionFactory" ref="sessionFactory"></property>

  </bean>

  <bean id="productManager" class="com.v512.example.service.impl.ProductManagerImpl">

  <property name="productDao" ref="productDao"></property>

  <property name="compassTemplate" ref="compassTemplate"></property>

  </bean>

 

  <bean id="productBean" class="com.v512.example.action.ProductAction" scope="prototype">

  <property name="productManager" ref="productManager"></property>

 

  </bean>

 

 

   <!-- 配置事务管理器 --> 

  <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

   <property name="sessionFactory">

     <ref local="sessionFactory"/>

   </property>

  </bean>

   

    <!-- 配置事务特性 ,配置add、delete和update开始的方法,事务传播特性为required-->      

    <tx:advice id="txAdvice" transaction-manager="transactionManager">

      <tx:attributes>

       <tx:method name="insert*" propagation="REQUIRED"/>

       <tx:method name="delete*" propagation="REQUIRED"/>

       <tx:method name="update*" propagation="REQUIRED"/>

       <tx:method name="*" read-only="true"/>

      </tx:attributes>

    </tx:advice>

   

    <!-- 配置那些类的方法进行事务管理,当前cn.com.jobedu.oa.service包中的子包、类中所有方法需要,还需要参考tx:advice的设置 -->

    <aop:config>

      <aop:pointcut id="allManagerMethod" expression="execution (* com.v512.example.service.*.*(..))"/>

      <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/>

    </aop:config>  

 

  </beans>

到此已经可以测试了
测试完插入之后,所有准备工作都已完成 现在我们来测下搜索
search.jap

Java代码

  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. <title>Insert title here</title>
  9. </head>
  10. <body>
  11. <s:form action="search.action" method="post">
  12. <s:textfield name="queryString" label="搜索产品"/>
  13. <s:submit></s:submit>
  14. </s:form>
  15. </body>
  16. </html>

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

    <%@taglib prefix="s" uri="/struts-tags" %>

    

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<s:form action="search.action" method="post">

<s:textfield name="queryString" label="搜索产品"/>

<s:submit></s:submit>

</s:form>

 

 

</body>

</html>

搜索后的结果页面
searchResults.jsp

Java代码

  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. <!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. <%
  13. if(((List)request.getAttribute("searchresults")).size()==0){
  14. %>
  15. no results found.
  16. <%} %>
  17. <table border="1">
  18. <s:iterator value="#request.searchresults">
  19. <tr><td>
  20. <s:property value="name"/>
  21. </td>
  22. <td>
  23. <s:property value="price"/></td>
  24. <td>
  25. <s:property value="brand"/></td>
  26. <td>
  27. <s:property value="description"/></td>
  28. </tr>
  29. </s:iterator>
  30. </table>
  31. </body>
  32. </html>

<%@ page language="java" contentType="text/html; charset=UTF-8"

  import="java.util.List"

    pageEncoding="UTF-8"%>

    <%@taglib prefix="s" uri="/struts-tags" %>

   

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<%

 

if(((List)request.getAttribute("searchresults")).size()==0){

  %>

  no results found.

<%} %>

 

<table border="1">

<s:iterator value="#request.searchresults">

<tr><td>

<s:property value="name"/>

</td>

<td>

 

<s:property value="price"/></td>

<td>

 

<s:property value="brand"/></td>

<td>

 

<s:property value="description"/></td>

</tr>

</s:iterator>

</table>

 

</body>

</html>

step10

另外得说下,该项目见索引的过程:服务器启动把需要建立索引的表的数据全部取出建立索引
在项目运行过程中,插入数据,容器检测到索引有变动,添加索引,这个可以自己测试

为此 要添加另外一个类:该类就是专门建索引用 注意包的位置

CompassIndexBuilder

Java代码

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

package com.v512.example.service.impl;

import org.compass.gps.CompassGps;

import org.springframework.beans.factory.InitializingBean;

 

 

/**

 * 通过quartz定时调度定时重建索引或自动随Spring ApplicationContext启动而重建索引的Builder.

 * 会启动后延时数秒新开线程调用compassGps.index()函数.

 * 默认会在Web应用每次启动时重建索引,可以设置buildIndex属性为false来禁止此功能.

 * 也可以不用本Builder, 编写手动调用compassGps.index()的代码.

 *

 */

public class CompassIndexBuilder implements InitializingBean {  

    // 是否需要建立索引,可被设置为false使本Builder失效.

    private boolean buildIndex = false;

 

    // 索引操作线程延时启动的时间,单位为秒

    private int lazyTime = 10;

 

    // Compass封装

    private CompassGps compassGps;

 

    // 索引线程

    private Thread indexThread = new Thread() {

 

        @Override

        public void run() {

            try {

                Thread.sleep(lazyTime * 1000);

                System.out.println("begin compass index...");

                long beginTime = System.currentTimeMillis();

                // 重建索引.

                // 如果compass实体中定义的索引文件已存在,索引过程中会建立临时索引,

                // 索引完成后再进行覆盖.

                compassGps.index();

                long costTime = System.currentTimeMillis() - beginTime;

                System.out.println("compss index finished.");

                System.out.println("costed " + costTime + " milliseconds");

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    };

 

    /**

     * 实现<code>InitializingBean</code>接口,在完成注入后调用启动索引线程.

     *

     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()

     */

    public void afterPropertiesSet() throws Exception {

        if (buildIndex) {

          //设置为后台线程

            indexThread.setDaemon(true);

            indexThread.setName("Compass Indexer");

            indexThread.start();

        }

    }

 

    public void setBuildIndex(boolean buildIndex) {

        this.buildIndex = buildIndex;

    }

 

    public void setLazyTime(int lazyTime) {

        this.lazyTime = lazyTime;

    }

 

    public void setCompassGps(CompassGps compassGps) {

        this.compassGps = compassGps;

    }

}

本项目中用的是paoding-analyzer
所以请在src目录下增加paoding-dic-home.properties文件

Java代码

  1. paoding.dic.home=C:/paoding/dic
  2. paoding.dic.detector.interval=60

paoding.dic.home=C:/paoding/dic

paoding.dic.detector.interval=60

over

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。