Struts2+Hibernate3.2+Spring2.5+Compass整合

阅读更多
之前学习了Compass  现在整合下ssh2+Compass

网上找了很多资料  都没一个完整的demo  本人写的demo供大家分享 一步到位
希望可以让大家少走点弯路  如果ssh2都不会整合的  我就不多说了
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的编写
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




    
        
            
            
        
        
            
        
        
            
        
        
            
        
        
            
        
    



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

step4applicationContext-compass.xml:




    
	
	


	
	    
		
			
				classpath:com/v512/example/model
			
		
		 
		
			/lucene/indexes
		
		
       
		
			
				com.v512.example.model.Product
			
		
		

        
		
			
				
					org.compass.spring.transaction.SpringSyncTransactionFactory
				
				  net.paoding.analysis.analyzer.PaodingAnalyzer 
			
		
        
		
	


	
		
			hibernateDevice
		
		
		
			true
		
	
	
	
		
		
			
				
					
				
			
		
	


	
		
	

	
	
		
		
		
	





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

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

step5
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);

}

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

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的实现
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 
 

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

step6
insertProduct.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>






添加信息


添加商品名称
商品名称
商品品牌
商品价格
商品描述
 

step7

编写action
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的配置文件如下




	
	
	
      
    
		
		
		
			insertOk.jsp
				
		
			searchResults.jsp
		
		
     
	




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

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




Insert title here


添加商品成功!




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


	
	
	
		contextConfigLocation
		/WEB-INF/applicationContext*.xml
	
	
	
		
			org.springframework.web.context.ContextLoaderListener
		
	
		
	
		lazyLoadingFilter
		
			org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
		
	
	
		
	
		struts2
		
			org.apache.struts2.dispatcher.FilterDispatcher
		
		
	
	
		

		lazyLoadingFilter
		*.action
	

	
		struts2
		/*
		
  
    index.jsp
  



applicationContext.xml



     
	
	  
	
	
	    
	    
	    
	    
	     
		 
		 
		 
		 
		 
		 
		 
	  
	  
	     
		 
		    
		      com/v512/example/model/Product.hbm.xml
		    
		 
	     
		    
		        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
		      
	     
	
	
	
	
	  

	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
			
	
		
			
		
	
    
           
    
    	
    		
    		
    		
    		
    	
    
    
    
    
    	
    	
       
	
	


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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="s" uri="/struts-tags" %>
    




Insert title here











搜索后的结果页面
searchResults.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	import="java.util.List"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="s" uri="/struts-tags" %>
    




Insert title here


<%

if(((List)request.getAttribute("searchresults")).size()==0){
	%>
	no results found.
<%} %>



step10

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

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

CompassIndexBuilder

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();
            }
        }
    };

    /**
     * 实现InitializingBean接口,在完成注入后调用启动索引线程.
     *
     * @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文件
paoding.dic.home=C:/paoding/dic
paoding.dic.detector.interval=60


over

ok  到此结束  恭喜你  你已经可以轻松的给自己的项目加上索引功能了







你可能感兴趣的:(Hibernate,Spring,lucene,Struts,配置管理)