hibernate search 查询和注释


简单查询用HQL,复杂查询用Critera

Criteria查询看这:http://blog.csdn.net/happyunbound/article/details/8135407

1.注释映射查询只可用HQL:

BasicCar.java:

       @Entity
       @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) 
       @Table(name="basiccar")
       @Indexed(index = "indexes/basiccar")
       @NamedQuery(name="hqlQuery",query="from BasicCar where id>:id")
       public class BasicCar implements java.io.Serializable

Test.java:

 //把criteria加到hibQuery
 org.hibernate.Query hibQuery =        fullTextSession.createFullTextQuery(query,BasicCar.class).setCriteriaQuery(criteria);         

   
//HQL查询,可放在hibQuery生成之后
   
hibQuery = session.getNamedQuery("hqlQuery");
   hibQuery.setInteger("id", 51);


2.QBC查询:

//QBC查询,放在hibQuery生成之前
Criteria criteria = fullTextSession.createCriteria(BasicCar.class);
criteria.add(Restrictions.like("factory", "%y%"));
//把criteria加到hibQuery
org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, BasicCar.class).setCriteriaQuery(criteria);


Test.java:

void queryEntity4() throws Exception{//QBC查询结合hibernate search

		session = sf.openSession();
		FullTextSession fullTextSession=Search.getFullTextSession(session);
		Transaction tx = fullTextSession.beginTransaction();
		
		QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity( BasicCar.class ).get();
		//查询是把salesman.address.city替换就可获取其他结果,如carName就可以直接获取本身的值,并不用通过关联来获取值
	    org.apache.lucene.search.Query query = qb.keyword().onFields("BaiscCarName").matching("hello").createQuery();

	    //QBC查询,放在hibQuery生成之前
	    Criteria criteria = fullTextSession.createCriteria(BasicCar.class);
	    criteria.add(Restrictions.like("factory", "%y%"));
	    //把criteria加到hibQuery
	    org.hibernate.Query hibQuery = fullTextSession.createFullTextQuery(query, BasicCar.class).setCriteriaQuery(criteria);
	    
	    //设置返回的结果个数
	    /*hibQuery.setFirstResult(10); //start from the 15th element从哪里开始   
	    hibQuery.setMaxResults(3); //return 10 elements  返回个数
         */	    
	    

	    List result = hibQuery.list();
	    for(int i=0;i


你可能感兴趣的:(Hibernate)