Lucene4.5.1之添加索引、更新索引、删除索引、查找数据

  写这篇文章的原因是我把几个东西合起来了,记录一下学习的脚步.

  主要做了这么一件事

       使用jpa2.0作为规范,eclipselink2.4作为实现 ,myeclipse2013作为工具映射oracle11g的表为实体(使用jpa反向工程自动生成相应实体的dao与interface,还有EntityManager的工具类)   

      使用poi读取word中的内容存放到lucene的索引库中

    最后

   1.添加索引
   2.更新索引----lucene的更新实际上 是先将索引删掉 然后重新添加索引 所以这里要注意一点 如果你的索引项不需要修改的话 不要将不需要修改的索引项传递到修改方法里面 不然          会造成未修改的索引项有多个
   3.删除索引
   4.根据条件,查找记录


详细步骤就不写了,代码里面都有注释:

  结构图:

Lucene4.5.1之添加索引、更新索引、删除索引、查找数据


  测试主函数: TestMain.java

/**
 * 
 */
package com.undergrowth.lucene.test;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TermQuery;


import com.undergrowth.bean.StuInf;
import com.undergrowth.bean.StuInfDAO;
import com.undergrowth.lucene.index.method.IndexAdd;
import com.undergrowth.lucene.index.method.IndexDelete;
import com.undergrowth.lucene.index.method.IndexUpdate;
import com.undergrowth.lucene.search.SearchUtils;
import com.undergrowth.utils.EntityManagerHelper;

/**
 * @author u1
 *
 */
public class TestMain {

	/**该测试代码主要做这么几件事
	 * 使用jpa2.0作为规范,eclipselink2.4作为实现 ,myeclipse2013作为工具映射oracle11g的表为实体(使用jpa反向工程自动生成相应实体的dao与interface,还有EntityManager的工具类)
	 * 使用poi读取word中的内容存放到lucene的索引库中
	 * 最后
	 * 1.添加索引
	 * 2.更新索引----lucene的更新实际上 是先将索引删掉 然后重新添加索引 所以这里要注意一点 如果你的索引项不需要修改的话 不要将不需要修改的索引项传递到修改方法里面 不然会造成未修改的索引项有多个
	 * 3.删除索引
	 * 4.根据条件,查找记录
	 * @param args
	 */
	public static Logger logger=LogManager.getLogger(TestMain.class);
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StuInfDAO entityDao=new StuInfDAO();
		List<StuInf> entityList=entityDao.findAll();
		disRecord(entityList);
		//删除掉已存在的所有索引
		IndexDelete.deleteIndexAll();
		//讲查询出来的记录添加到索引中
		IndexAdd.addIndex(entityList);
		//查询记录
		TermQuery query=new TermQuery(new Term("content", "搜索引擎"));
		//TermQuery query=new TermQuery(new Term("path", "lucene"));
		List<Document> resultList=SearchUtils.search(query,10);
		disResultRecord(resultList);
		
		//更新数据源
	    EntityManagerHelper.beginTransaction();
	    for (StuInf entity : entityList) {
	    	entity.setBirthday(new Timestamp(new Date().getTime()));
			entityDao.update(entity);
		}
	    EntityManagerHelper.commit();
	    //清除结果集
	    resultList.clear();
	    //重新装载结果集
	    for (StuInf stuInf : entityList) {
			Document document=new Document();
			document.add(new TextField("id", stuInf.getId(),Field.Store.YES));
			document.add(new TextField("birthday", stuInf.getBirthday().toString(),Field.Store.YES));
			document.add(new TextField("path",stuInf.getDescriptPath(),Field.Store.YES));
			document.add(new TextField("content",EntityManagerHelper.getDescriptContent(stuInf.getDescriptPath()),Field.Store.YES));
			resultList.add(document);
		}
	  //更新索引
		IndexUpdate.updateIndex(new Term("content", "搜索引擎"),resultList);
	  //再次搜索
		TermQuery queryUpdate=new TermQuery(new Term("content", "搜索引擎"));
		resultList=SearchUtils.search(queryUpdate,10);
		disResultRecord(resultList);
		//显示未更新的索引的记录
		queryUpdate=new TermQuery(new Term("content", "甲骨文"));
		resultList=SearchUtils.search(queryUpdate,10);
		disResultRecord(resultList);
	}

	//显示结果集
	private static void disResultRecord(List<Document> resultList) {
		// TODO Auto-generated method stub
		logger.error("开始显示结果!!");
		for (Document doc : resultList) {
			/*System.out.println(stuInf);*/
			logger.error("\n日期:"+doc.get("birthday")+"\n描述信息为:"+doc.get("content"));
		}
	}

	//显示查询的记录
	private static void disRecord(List<StuInf> entityList) {
		for (StuInf stuInf : entityList) {
			/*System.out.println(stuInf);*/
			logger.debug(stuInf);
		}
	}

}

索引删除 IndexDelete.java

package com.undergrowth.lucene.index.method;

import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.IndexWriter;
import com.undergrowth.lucene.index.utils.IndexUtils;

public class IndexDelete {

	private static Logger logger=LogManager.getLogger();
	
	//删除索引
	public static void deleteIndexAll() {
		// TODO Auto-generated method stub
		IndexWriter writer=IndexUtils.getIndexWrite();
		try {
			//删除所有索引项
			writer.deleteAll();
			writer.close();
			logger.info("成功删除索引文件");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

索引添加 IndexAdd.java

/**
 * 
 */
package com.undergrowth.lucene.index.method;


import java.io.File;
import java.io.IOException;
import java.util.List;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.undergrowth.bean.StuInf;
import com.undergrowth.lucene.index.utils.IndexUtils;
import com.undergrowth.utils.EntityManagerHelper;

/**
 * @author u1
 *
 */
public class IndexAdd {

	private static Logger logger=LogManager.getLogger(IndexAdd.class);
	
	//添加索引
	public static void addIndex(List<StuInf> entityList) {
		// TODO Auto-generated method stub
		IndexWriter writer=null;
		try {
			writer=IndexUtils.getIndexWrite();
			for (StuInf stuInf : entityList) {
				Document document=new Document();
				document.add(new TextField("id", stuInf.getId(),Field.Store.YES));
				document.add(new TextField("birthday", stuInf.getBirthday().toString(),Field.Store.YES));
				document.add(new TextField("path",stuInf.getDescriptPath(),Field.Store.YES));
				document.add(new TextField("content",EntityManagerHelper.getDescriptContent(stuInf.getDescriptPath()),Field.Store.YES));
				//添加索引项
				writer.addDocument(document);
			}
			//提交索引 关闭所有关联文件
			writer.close();
			logger.info("添加了"+entityList.size()+"个索引");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	
	
}


查询工具 SearchUtils.java

/**
 * 
 */
package com.undergrowth.lucene.search;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.undergrowth.lucene.index.method.IndexAdd;
import com.undergrowth.lucene.index.utils.IndexUtils;

/**
 * @author u1
 *
 */
public class SearchUtils {

	private static Logger logger=LogManager.getLogger(SearchUtils.class);
	
	//根据查询条件 返回结果集
	public static List<Document> search(TermQuery query,int n) {
		// TODO Auto-generated method stub
		
		List<Document> list=new ArrayList<Document>();
		Directory directory=IndexUtils.getLuceneIndexPath();
		try {
			IndexReader reader=DirectoryReader.open(directory);
			IndexSearcher searcher=new IndexSearcher(reader);
			TopDocs docs=searcher.search(query, n);
			logger.info("找到了"+docs.totalHits+"个元素");
			ScoreDoc[] scoreDocs=docs.scoreDocs;
			for (ScoreDoc scoreDoc : scoreDocs) {
				Document document=searcher.doc(scoreDoc.doc);
				list.add(document);
			}
			reader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	
}

索引更新 IndexUpdate.java

package com.undergrowth.lucene.index.method;

import java.io.IOException;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;

import com.undergrowth.lucene.index.utils.IndexUtils;

public class IndexUpdate {

	//更新索引
	public static void updateIndex(Term term,List<Document> resultList) {
		// TODO Auto-generated method stub
		IndexWriter writer=IndexUtils.getIndexWrite();
		
		try {
			writer.updateDocuments(term, resultList);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	

}

索引工具 IndexUtils.java

package com.undergrowth.lucene.index.utils;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.undergrowth.utils.EntityManagerHelper;

public class IndexUtils {
	
	public static Directory getLuceneIndexPath(){
		//获取索引的文件路径
		File path=new File(EntityManagerHelper.getProperty("luceneIndex"));
		//判断文件是否存在 不存在 则创建
		if(!path.exists()) path.mkdirs();
		Directory dictory=null;
		try {
			
			dictory = FSDirectory.open(path);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dictory;
	}

   //获取索引写对象
	public static IndexWriter getIndexWrite() {
		IndexWriter writer=null;
		Directory directory=getLuceneIndexPath();
		SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer(Version.LUCENE_45);
		//Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_45);
		IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_45, analyzer);
		try {
			writer=new IndexWriter(directory, config);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return writer;
	}
	
	
}


实体管理器帮助类  EntityManagerHelper.java

package com.undergrowth.utils;



import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hwpf.HWPFDocument;
/**
 * @author MyEclipse Persistence Tools
 */
public class EntityManagerHelper {
	
	private static final EntityManagerFactory emf; 
	private static final ThreadLocal<EntityManager> threadLocal;
	private static final Logger logger;
	
	static {
		emf = Persistence.createEntityManagerFactory("Lucene4.5.1"); 		
		threadLocal = new ThreadLocal<EntityManager>();
		logger = LogManager.getLogger(EntityManagerHelper.class);
	}
		
	public static EntityManager getEntityManager() {
		EntityManager manager = threadLocal.get();		
		if (manager == null || !manager.isOpen()) {
			manager = emf.createEntityManager();
			threadLocal.set(manager);
		}
		return manager;
	}
	
	 public static void closeEntityManager() {
        EntityManager em = threadLocal.get();
        threadLocal.set(null);
        if (em != null) em.close();
    }
    
    public static void beginTransaction() {
    	getEntityManager().getTransaction().begin();
    }
    
    public static void commit() {
    	getEntityManager().getTransaction().commit();
    }  
    
    public static void rollback() {
    	getEntityManager().getTransaction().rollback();
    } 
    
    public static Query createQuery(String query) {
		return getEntityManager().createQuery(query);
	}
	
	public static void log(String info, Level level, Throwable ex) {
    	logger.log(level, info, ex);
    }
    
	//获取配置文件路径
	public static String getProperty(String key)
	{
		String value="";
		InputStream is=EntityManagerHelper.class.getClassLoader().getResourceAsStream("config.properties");
		Properties properties=new Properties();
		try {
			properties.load(is);
			value=properties.getProperty(key);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
	}

	//根据路径 获取word中的内容
	public static String getDescriptContent(String descriptPath) {
		// TODO Auto-generated method stub
		String content="";
		InputStream is=null;
		try {
			is = new FileInputStream(descriptPath);
			HWPFDocument document=new HWPFDocument(is);
			content=document.getDocumentText();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(is!=null) is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return content;
	}
}

StuInf.java文件

package com.undergrowth.bean;

import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * StuInf entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "STU_INF", schema = "UNDER")
public class StuInf implements java.io.Serializable {

	// Fields

	private String id;
	private Timestamp birthday;
	private String descriptPath;

	// Constructors

	/** default constructor */
	public StuInf() {
	}

	/** minimal constructor */
	public StuInf(String id) {
		this.id = id;
	}

	/** full constructor */
	public StuInf(String id, Timestamp birthday, String descriptPath) {
		this.id = id;
		this.birthday = birthday;
		this.descriptPath = descriptPath;
	}

	// Property accessors
	@Id
	@Column(name = "ID", unique = true, nullable = false, length = 50)
	public String getId() {
		return this.id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Column(name = "BIRTHDAY", length = 7)
	public Timestamp getBirthday() {
		return this.birthday;
	}

	public void setBirthday(Timestamp birthday) {
		this.birthday = birthday;
	}

	@Column(name = "DESCRIPT_PATH", length = 50)
	public String getDescriptPath() {
		return this.descriptPath;
	}

	public void setDescriptPath(String descriptPath) {
		this.descriptPath = descriptPath;
	}

	@Override
	public String toString() {
		return "StuInf [id=" + id + ", birthday=" + birthday
				+ ", descriptPath=" + descriptPath + "]";
	}

	
	
}

StuInfDao.java

package com.undergrowth.bean;

import java.sql.Timestamp;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.logging.log4j.Level;

import com.undergrowth.utils.EntityManagerHelper;

/**
 * A data access object (DAO) providing persistence and search support for
 * StuInf entities. Transaction control of the save(), update() and delete()
 * operations must be handled externally by senders of these methods or must be
 * manually added to each of these methods for data to be persisted to the JPA
 * datastore.
 * 
 * @see com.undergrowth.bean.StuInf
 * @author MyEclipse Persistence Tools
 */
public class StuInfDAO implements IStuInfDAO {
	// property constants
	public static final String DESCRIPT_PATH = "descriptPath";

	private EntityManager getEntityManager() {
		return EntityManagerHelper.getEntityManager();
	}

	/**
	 * Perform an initial save of a previously unsaved StuInf entity. All
	 * subsequent persist actions of this entity should use the #update()
	 * method. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#persist(Object)
	 * EntityManager#persist} operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * StuInfDAO.save(entity);
	 * EntityManagerHelper.commit();
	 * </pre>
	 * 
	 * @param entity
	 *            StuInf entity to persist
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void save(StuInf entity) {
		EntityManagerHelper.log("saving StuInf instance", Level.INFO, null);
		try {
			getEntityManager().persist(entity);
			EntityManagerHelper.log("save successful", Level.INFO, null);
		} catch (RuntimeException re) {
			EntityManagerHelper.log("save failed", Level.INFO, re);
			throw re;
		}
	}

	/**
	 * Delete a persistent StuInf entity. This operation must be performed
	 * within the a database transaction context for the entity's data to be
	 * permanently deleted from the persistence store, i.e., database. This
	 * method uses the {@link javax.persistence.EntityManager#remove(Object)
	 * EntityManager#delete} operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * StuInfDAO.delete(entity);
	 * EntityManagerHelper.commit();
	 * entity = null;
	 * </pre>
	 * 
	 * @param entity
	 *            StuInf entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(StuInf entity) {
		EntityManagerHelper.log("deleting StuInf instance", Level.INFO, null);
		try {
			entity = getEntityManager().getReference(StuInf.class,
					entity.getId());
			getEntityManager().remove(entity);
			EntityManagerHelper.log("delete successful", Level.INFO, null);
		} catch (RuntimeException re) {
			EntityManagerHelper.log("delete failed", Level.INFO, re);
			throw re;
		}
	}

	/**
	 * Persist a previously saved StuInf entity and return it or a copy of it to
	 * the sender. A copy of the StuInf entity parameter is returned when the
	 * JPA persistence mechanism has not previously been tracking the updated
	 * entity. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
	 * operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * entity = StuInfDAO.update(entity);
	 * EntityManagerHelper.commit();
	 * </pre>
	 * 
	 * @param entity
	 *            StuInf entity to update
	 * @return StuInf the persisted StuInf entity instance, may not be the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public StuInf update(StuInf entity) {
		EntityManagerHelper.log("updating StuInf instance", Level.INFO, null);
		try {
			StuInf result = getEntityManager().merge(entity);
			EntityManagerHelper.log("update successful", Level.INFO, null);
			return result;
		} catch (RuntimeException re) {
			EntityManagerHelper.log("update failed", Level.INFO, re);
			throw re;
		}
	}

	public StuInf findById(String id) {
		EntityManagerHelper.log("finding StuInf instance with id: " + id,
				Level.INFO, null);
		try {
			StuInf instance = getEntityManager().find(StuInf.class, id);
			return instance;
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find failed", Level.INFO, re);
			throw re;
		}
	}

	/**
	 * Find all StuInf entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the StuInf property to query
	 * @param value
	 *            the property value to match
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            number of results to return.
	 * @return List<StuInf> found by query
	 */
	@SuppressWarnings("unchecked")
	public List<StuInf> findByProperty(String propertyName, final Object value,
			final int... rowStartIdxAndCount) {
		EntityManagerHelper.log("finding StuInf instance with property: "
				+ propertyName + ", value: " + value, Level.INFO, null);
		try {
			final String queryString = "select model from StuInf model where model."
					+ propertyName + "= :propertyValue";
			Query query = getEntityManager().createQuery(queryString);
			query.setParameter("propertyValue", value);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find by property name failed",
					Level.INFO, re);
			throw re;
		}
	}

	public List<StuInf> findByDescriptPath(Object descriptPath,
			int... rowStartIdxAndCount) {
		return findByProperty(DESCRIPT_PATH, descriptPath, rowStartIdxAndCount);
	}

	/**
	 * Find all StuInf entities.
	 * 
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<StuInf> all StuInf entities
	 */
	@SuppressWarnings("unchecked")
	public List<StuInf> findAll(final int... rowStartIdxAndCount) {
		EntityManagerHelper.log("finding all StuInf instances", Level.INFO,
				null);
		try {
			final String queryString = "select model from StuInf model";
			Query query = getEntityManager().createQuery(queryString);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find all failed", Level.INFO, re);
			throw re;
		}
	}

}

IStuInfDao.java

package com.undergrowth.bean;

import java.sql.Timestamp;
import java.util.List;

/**
 * Interface for StuInfDAO.
 * 
 * @author MyEclipse Persistence Tools
 */

public interface IStuInfDAO {
	/**
	 * Perform an initial save of a previously unsaved StuInf entity. All
	 * subsequent persist actions of this entity should use the #update()
	 * method. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#persist(Object)
	 * EntityManager#persist} operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * IStuInfDAO.save(entity);
	 * EntityManagerHelper.commit();
	 * </pre>
	 * 
	 * @param entity
	 *            StuInf entity to persist
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void save(StuInf entity);

	/**
	 * Delete a persistent StuInf entity. This operation must be performed
	 * within the a database transaction context for the entity's data to be
	 * permanently deleted from the persistence store, i.e., database. This
	 * method uses the {@link javax.persistence.EntityManager#remove(Object)
	 * EntityManager#delete} operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * IStuInfDAO.delete(entity);
	 * EntityManagerHelper.commit();
	 * entity = null;
	 * </pre>
	 * 
	 * @param entity
	 *            StuInf entity to delete
	 * @throws RuntimeException
	 *             when the operation fails
	 */
	public void delete(StuInf entity);

	/**
	 * Persist a previously saved StuInf entity and return it or a copy of it to
	 * the sender. A copy of the StuInf entity parameter is returned when the
	 * JPA persistence mechanism has not previously been tracking the updated
	 * entity. This operation must be performed within the a database
	 * transaction context for the entity's data to be permanently saved to the
	 * persistence store, i.e., database. This method uses the
	 * {@link javax.persistence.EntityManager#merge(Object) EntityManager#merge}
	 * operation.
	 * 
	 * <pre>
	 * EntityManagerHelper.beginTransaction();
	 * entity = IStuInfDAO.update(entity);
	 * EntityManagerHelper.commit();
	 * </pre>
	 * 
	 * @param entity
	 *            StuInf entity to update
	 * @return StuInf the persisted StuInf entity instance, may not be the same
	 * @throws RuntimeException
	 *             if the operation fails
	 */
	public StuInf update(StuInf entity);

	public StuInf findById(String id);

	/**
	 * Find all StuInf entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the StuInf property to query
	 * @param value
	 *            the property value to match
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<StuInf> found by query
	 */
	public List<StuInf> findByProperty(String propertyName, Object value,
			int... rowStartIdxAndCount);

	public List<StuInf> findByDescriptPath(Object descriptPath,
			int... rowStartIdxAndCount);

	/**
	 * Find all StuInf entities.
	 * 
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            count of results to return.
	 * @return List<StuInf> all StuInf entities
	 */
	public List<StuInf> findAll(int... rowStartIdxAndCount);
}

log4的配置文件log4j2.xml

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

<Configuration status="off" name="test">  
    <!-- 添加输出源 -->  
    <Appenders>  
        <!-- 添加控制台输出源  
        PatternLayout用于格式化日志文本 并输出到指定的输出源    
         -->  
        <Console name="out" target="SYSTEM_OUT">  
            <PatternLayout pattern="%d{yyyy-MMM-dd HH:mm:ss} [%t] %-5p: %m%n"></PatternLayout>  
        </Console>  
    </Appenders>  
    <!-- 添加记录器 -->  
    <Loggers>  
        <!-- 配置根记录器 如果不设置的话  level为error appender为控制台 -->  
        <root level="trace">  
            <AppenderRef ref="out" />  
        </root>  
    </Loggers>  
</Configuration>  


控制台结果集:

2013-十二月-08 21:23:37 [main] INFO : finding all StuInf instances
[EL Info]: 2013-12-08 21:23:39.112--ServerSession(61130164)--EclipseLink, version: Eclipse Persistence Services - 2.4.2.v20130514-5956486
[EL Info]: connection: 2013-12-08 21:23:39.82--ServerSession(61130164)--file:/E:/learnsoftware/java/AndroidDevelop/myeclipse_2013_code/Lucene4.5.1/bin/_Lucene4.5.1 login successful
2013-十二月-08 21:23:40 [main] DEBUG: StuInf [id=9978F96DCAE447E59E7772D978E544F9, birthday=2013-12-08 21:12:56.0, descriptPath=E:\lucene\doc\oracle.doc]
2013-十二月-08 21:23:40 [main] DEBUG: StuInf [id=7FA82B9F2C4F4163AAEAB74EB3E2E79C, birthday=2013-12-08 21:12:56.0, descriptPath=E:\lucene\doc\google.doc]
2013-十二月-08 21:23:40 [main] DEBUG: StuInf [id=BA272904CA1A4ED1816965AB93424312, birthday=2013-12-08 21:12:56.0, descriptPath=E:\lucene\doc\baidu.doc]
2013-十二月-08 21:23:40 [main] INFO : 成功删除索引文件
2013-十二月-08 21:23:42 [main] INFO : 添加了3个索引
2013-十二月-08 21:23:42 [main] INFO : 找到了2个元素
2013-十二月-08 21:23:42 [main] ERROR: 开始显示结果!!
2013-十二月-08 21:23:42 [main] ERROR: 
日期:2013-12-08 21:12:56.0
描述信息为:百度(Nasdaq简称:BIDU)是全球最大的中文搜索引擎,2000年1月由李彦宏、徐勇两人创立于北京中关村,
致力于向人们提供“简单,可依赖”的信息获取方式。“百度”二字源于中国宋朝词人辛弃疾的《青玉案?元夕》词句“众里寻他千百度”,
象征着百度对中文信息检索技术的执著追求。

2013-十二月-08 21:23:42 [main] ERROR: 
日期:2013-12-08 21:12:56.0
描述信息为:谷歌公司(英语:Google Inc.,NASDAQ:GOOG、FWB:GGQ1,官方中文译名为谷歌),是一家美国的跨国科技企业,致力于互联网搜索、云计算、广告技术等领域,开发并提供大量基于互联网的产品与服务,其主要利润来自于AdWords等广告服务。 Google由当时在斯坦福大学攻读理工博士的拉里?佩奇和谢尔盖?布卢姆共同创建,因此两人也被称为“Google Guys”。1998年9月4日,Google以私营公司的形式创立,设计并管理一个互联网搜索引擎“Google搜索”;Google网站则于1999年下半年启用。2004年8月19日,Google公司的股票在纳斯达克上市,后来被称为“三驾马车”的公司两位共同创始人与出任首席执行官的埃里克?施密特在当时承诺:共同在Google工作至少二十年,即至2024年止。创始之初,Google官方的公司使命为“集成全球范围的信息,使人人皆可访问并从中受益”(To organize the world's information and make it universally accessible and useful);而非正式的口号则为“不作恶”(Don't be evil),由工程师阿米特?帕特尔(Amit Patel)所创,并得到了保罗?布赫海特的支持。Google公司的总部称为“Googleplex”,位于美国加州圣克拉拉县的芒廷维尤。2011年4月,佩奇接替施密特担任首席执行官。

2013-十二月-08 21:23:42 [main] INFO : updating StuInf instance
2013-十二月-08 21:23:42 [main] INFO : update successful
2013-十二月-08 21:23:42 [main] INFO : updating StuInf instance
2013-十二月-08 21:23:42 [main] INFO : update successful
2013-十二月-08 21:23:42 [main] INFO : updating StuInf instance
2013-十二月-08 21:23:42 [main] INFO : update successful
2013-十二月-08 21:23:42 [main] INFO : 找到了2个元素
2013-十二月-08 21:23:42 [main] ERROR: 开始显示结果!!
2013-十二月-08 21:23:42 [main] ERROR: 
日期:2013-12-08 21:23:42.312
描述信息为:百度(Nasdaq简称:BIDU)是全球最大的中文搜索引擎,2000年1月由李彦宏、徐勇两人创立于北京中关村,
致力于向人们提供“简单,可依赖”的信息获取方式。“百度”二字源于中国宋朝词人辛弃疾的《青玉案?元夕》词句“众里寻他千百度”,
象征着百度对中文信息检索技术的执著追求。

2013-十二月-08 21:23:42 [main] ERROR: 
日期:2013-12-08 21:23:42.312
描述信息为:谷歌公司(英语:Google Inc.,NASDAQ:GOOG、FWB:GGQ1,官方中文译名为谷歌),是一家美国的跨国科技企业,致力于互联网搜索、云计算、广告技术等领域,开发并提供大量基于互联网的产品与服务,其主要利润来自于AdWords等广告服务。 Google由当时在斯坦福大学攻读理工博士的拉里?佩奇和谢尔盖?布卢姆共同创建,因此两人也被称为“Google Guys”。1998年9月4日,Google以私营公司的形式创立,设计并管理一个互联网搜索引擎“Google搜索”;Google网站则于1999年下半年启用。2004年8月19日,Google公司的股票在纳斯达克上市,后来被称为“三驾马车”的公司两位共同创始人与出任首席执行官的埃里克?施密特在当时承诺:共同在Google工作至少二十年,即至2024年止。创始之初,Google官方的公司使命为“集成全球范围的信息,使人人皆可访问并从中受益”(To organize the world's information and make it universally accessible and useful);而非正式的口号则为“不作恶”(Don't be evil),由工程师阿米特?帕特尔(Amit Patel)所创,并得到了保罗?布赫海特的支持。Google公司的总部称为“Googleplex”,位于美国加州圣克拉拉县的芒廷维尤。2011年4月,佩奇接替施密特担任首席执行官。

2013-十二月-08 21:23:42 [main] INFO : 找到了2个元素
2013-十二月-08 21:23:42 [main] ERROR: 开始显示结果!!
2013-十二月-08 21:23:42 [main] ERROR: 
日期:2013-12-08 21:12:56.0
描述信息为:Oracle Database,又名Oracle RDBMS,或简称Oracle。是甲骨文公司的一款关系数据库管理系统。到目前仍在数据库市场上占有主要份额。劳伦斯?埃里森和他的朋友,之前的同事Bob Miner和Ed Oates在1977年建立了软件开发实验室咨询公司(SDL,Software Development Laboratories)。

2013-十二月-08 21:23:42 [main] ERROR: 
日期:2013-12-08 21:23:42.308
描述信息为:Oracle Database,又名Oracle RDBMS,或简称Oracle。是甲骨文公司的一款关系数据库管理系统。到目前仍在数据库市场上占有主要份额。劳伦斯?埃里森和他的朋友,之前的同事Bob Miner和Ed Oates在1977年建立了软件开发实验室咨询公司(SDL,Software Development Laboratories)。


oracle 表结构

--创建学生信息表
drop table stu_inf;
create table stu_inf(
       id varchar2(50) default sys_guid(),
       birthday date default sysdate,
       descript_path varchar2(50),
       primary key (id)
);
 --添加注释
 comment on column stu_inf.id is '默认值为guid,产生一个唯一的标示符';
 comment on column stu_inf.descript_path is '用于存放描述个人信息的word路径';
 
 insert into stu_inf(descript_path) values('E:\lucene\doc\oracle.doc');
  insert into stu_inf(descript_path) values('E:\lucene\doc\google.doc');
   insert into stu_inf(descript_path) values('E:\lucene\doc\baidu.doc');



你可能感兴趣的:(Lucene)