注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

无线时代辐射无穷

抓紧生宝宝,小心辐射

 
 
 

日志

 
 

hibernate search 与 lucene 结合一点点总结  

2009-09-23 18:23:15|  分类: hibernate |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

例子:javaeye的例子http://wishlife.javaeye.com/blog/186873

hibernate.cfg.xml配置:

<hibernate-configuration>
    <session-factory>   
         <mapping class="com.splashnote.model.User"/>

            ....

            ...
         <event type="post-update">
            <listener class="org.hibernate.search.event.FullTextIndexEventListener"/>
        </event>
        <event type="post-insert">
            <listener class="org.hibernate.search.event.FullTextIndexEventListener"/>
        </event>
        <event type="post-delete">
            <listener class="org.hibernate.search.event.FullTextIndexEventListener"/>
        </event>
      </session-factory>
</hibernate-configuration>

 

session:

 

 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">    ${hibernate.dialect} </prop>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
    <prop key="hibernate.show_sql">  ${hibernate.show_sql}</prop>
    <prop key="hibernate.format_sql"> false</prop>
    <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
    <!-- Hibernate search Lucene index directory config -->
    <prop key="hibernate.search.default.directory_provider">${hibernate.search.default.directory_provider}</prop>
    <prop key="hibernate.search.default.indexBase">${hibernate.search.default.indexBase}</prop>
   </props>
  </property>

 </bean>

 

 

jdbc.property:

 


# Database config
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/splash_db?useUnicode=true&amp;characterEncoding=UTF8
jdbc.username=root
jdbc.password=root

hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=false
hibernate.generate_statistics=false
hibernate.format_sql=false
  
# the default directory provider
hibernate.search.default.directory_provider = org.hibernate.search.store.FSDirectoryProvider

# the default base directory for the indexes
hibernate.search.default.indexBase=C:/Test/lucene/indexes/
  

 

mode: user表:

 

/*
 *####################################################################
 *   Copyright (C) 2000-2008 SplashNote Systems, Inc.
 *      ALL RIGHTS RESERVED
 *####################################################################
 */

package com.splashnote.model;

import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.hibernate.search.annotations.Analyzer;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;

import javax.persistence.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * This class represents the basic "user" object that allows for authentication
 * and user management.  It implements Acegi Security's UserDetails interface.
 *
 * @author praveen
 */
@Entity
@Table(name="user")
@Indexed(index="User")
@Analyzer
public class User extends BaseObject implements UserDetails {
    private static final long serialVersionUID = 3832626162173359411L;

    private Long   id;
    private Long   randomId;
    private String username;                    // required, {Email}
    private String screenName;
    private String password;                    // required
    private String confirmPassword;
    private String externalURL;
    private boolean avatarFlag ;
       
    private Set<Role> roles = new HashSet<Role>();   
    private Integer version;
    private boolean enabled;
    private boolean accountExpired;
    private boolean accountLocked;
    private boolean credentialsExpired;
   
    private Date dateCreated;
 private Date dateUpdated;
 private Date dateLastLogin;
 
 private int friendStatus;
 
 private int sitePrivacy; // Site privacy settings  private,public,friends...more family
 private boolean friendsEmailNotify; // email notification on friends request and friends signup
 private String displayHeader="00";//check for special accounts like CSPAadmin, startupcv
 private boolean newsNotify;
 private boolean commentsNotify;
 private boolean featuredsEnabled;
 private boolean toolTipFlagNotify;
 
 private boolean friendSignUpEmailNotification;
 /**
     * Default constructor - creates a new instance with no values set.
     */
    public User() {}

    /**
     * Create a new instance and set the username.
     * @param username login name for user.
     */
    public User(final String username) {
        this.username = username;
    }

    /*
    @javax.persistence.SequenceGenerator(
      name="SEQ_GEN",
      sequenceName="my_sequence",
      initialValue =11111,
      allocationSize=1
      )
      */
 @Id @GeneratedValue(strategy=GenerationType.AUTO)
 @DocumentId
    public Long getId() {
        return id;
    }

    public Long getRandomId() {
  return randomId;
 }

 @Column(nullable=false,length=50,unique=true)
 @Field(index=Index.UN_TOKENIZED, store=Store.YES)
    public String getUsername() {
        return username;
    }

    @Column(nullable=false,length=50,unique=true)
//    @Field(index=Index.UN_TOKENIZED, store=Store.YES)
    @Field(index=Index.UN_TOKENIZED, store=Store.YES,analyzer = @Analyzer(impl = StandardAnalyzer.class))
    public String getScreenName() {
  return screenName;
 }

   
    @Column(nullable=false)
    public String getPassword() {
        return password;
    }

    @Transient
    public String getConfirmPassword() {
        return confirmPassword;
    }

   
    /*//@Column(name="password_hint")
    public String getPasswordHint() {
        return passwordHint;
    }
   
    @Column(length=50)//nullable=false,name="first_name",
    public String getFirstName() {
        return firstName;
    }

    @Column(length=50)//nullable=false,name="last_name",
    public String getLastName() {
        return lastName;
    }

   
    @Column(nullable=false,unique=true)
    public String getEmail() {
        return email;
    }
   
    //@Column(name="phone_number")
    public String getPhoneNumber() {
        return phoneNumber;
    }

   

   
    @Transient
    public String getFullName() {
        return firstName + ' ' + lastName;
    }

    @Embedded
    public Address getAddress() {
        return address;
    }
    */

    public String getExternalURL() {
  return externalURL;
 }

   
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name="user_role",
            joinColumns = { @JoinColumn( name="userId") },
            inverseJoinColumns = @JoinColumn( name="roleId")
    )   
    public Set<Role> getRoles() {
        return roles;
    }
 
    //social thingy adding a friends list
    //self referential many-to-many table
    /*
 @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
            name="user_user",
            joinColumns = {@JoinColumn( name="userId") },
            inverseJoinColumns = @JoinColumn( name="friendsId")
    )   
    public Set<User> getUsers() {
  return users;
 }
    */
    /**
     * Convert user roles to LabelValue objects for convenience.
     * @return a list of LabelValue objects with role information
     */
    @Transient
    public List<LabelValue> getRoleList() {
        List<LabelValue> userRoles = new ArrayList<LabelValue>();

        if (this.roles != null) {
            for (Role role : roles) {
                // convert the user's roles to LabelValue Objects
                userRoles.add(new LabelValue(role.getName(), role.getName()));
            }
        }

        return userRoles;
    }

    /**
     * Adds a role for the user
     * @param role the fully instantiated role
     */
    public void addRole(Role role) {
        getRoles().add(role);
    }
   
    /**
     * @see org.acegisecurity.userdetails.UserDetails#getAuthorities()
     * @return GrantedAuthority[] an array of roles.
     */
    @Transient
    public GrantedAuthority[] getAuthorities() {
        return roles.toArray(new GrantedAuthority[0]);
    }

    @Version
    public Integer getVersion() {
        return version;
    }
   
    @Column(nullable=false)
    public boolean isAvatarFlag() {
  return avatarFlag;
 }

 public void setAvatarFlag(boolean avatarFlag) {
  this.avatarFlag = avatarFlag;
 }

 //@Column(name="account_enabled")
// @Field(index=Index.NO, store=Store.YES)
    public boolean isEnabled() {
        return enabled;
    }
   
    @Column(nullable=false)//name="account_expired",
    public boolean isAccountExpired() {
        return accountExpired;
    }
   
    /**
     * @see org.acegisecurity.userdetails.UserDetails#isAccountNonExpired()
     */
    @Transient
    public boolean isAccountNonExpired() {
        return !isAccountExpired();
    }

    @Column(nullable=false)//name="account_locked",
    public boolean isAccountLocked() {
        return accountLocked;
    }
   
    /**
     * @see org.acegisecurity.userdetails.UserDetails#isAccountNonLocked()
     */
    @Transient
    public boolean isAccountNonLocked() {
        return !isAccountLocked();
    }

    @Column(nullable=false)//name="credentials_expired",
    public boolean isCredentialsExpired() {
        return credentialsExpired;
    }
   
    /**
     * @see org.acegisecurity.userdetails.UserDetails#isCredentialsNonExpired()
     */
    @Transient
    public boolean isCredentialsNonExpired() {
        return !credentialsExpired;
    }
   
    //@Column(updatable = false)
    public Date getDateCreated() {
  return dateCreated;
 }

    @Temporal(TemporalType.TIMESTAMP)
 @Column(columnDefinition = "timestamp", updatable = false)//name="date_updated",
 public Date getDateUpdated() {
  return dateUpdated;
 }

    public int getSitePrivacy() {
  return sitePrivacy;
 }

    @Column(nullable=false)//columnDefinition = "BIT(1) default '1'"   
 public boolean isFriendsEmailNotify() {
  return friendsEmailNotify;
 }
    @Column(nullable=false)//columnDefinition = "BIT(1) default '1'"   
 public boolean isToolTipFlagNotify() {
  return toolTipFlagNotify;
 }
    @Column(nullable=false)
 public boolean isFriendSignUpEmailNotification() {
  return friendSignUpEmailNotification;
 }
   
 @Transient
    public int getFriendStatus() {
  return friendStatus;
 }

 

 ////////// Add the setters
 public void setId(Long id) {
        this.id = id;
    }
   
 public void setRandomId(Long randomId) {
  this.randomId = randomId;
 }
 
    public void setUsername(String username) {
        this.username = username;
    }
   
    public void setScreenName(String screenName) {
  this.screenName = screenName;
 }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    /*
    public void setPasswordHint(String passwordHint) {
        this.passwordHint = passwordHint;
    }


    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }


    public void setAddress(Address address) {
        this.address = address;
    }

    */

 public void setExternalURL(String externalURL) {
  this.externalURL = externalURL;
 }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }
   
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void setAccountExpired(boolean accountExpired) {
        this.accountExpired = accountExpired;
    }
   
    public void setAccountLocked(boolean accountLocked) {
        this.accountLocked = accountLocked;
    }

    public void setCredentialsExpired(boolean credentialsExpired) {
        this.credentialsExpired = credentialsExpired;
    }
   
    public void setDateCreated(Date dateCreated) {
  this.dateCreated = dateCreated;
 }

 public void setDateUpdated(Date dateUpdated) {
  this.dateUpdated = dateUpdated;
 }
 
 public void setFriendStatus(int friendStatus) {
  this.friendStatus = friendStatus;
 }
   
 public void setSitePrivacy(int sitePrivacy) {
  this.sitePrivacy = sitePrivacy;
 }

 public void setFriendsEmailNotify(boolean friendsEmailNotify) {
  this.friendsEmailNotify = friendsEmailNotify;
 }
 
 public void setFriendSignUpEmailNotification(boolean friendSignUpEmailNotification) {
  this.friendSignUpEmailNotification = friendSignUpEmailNotification;
 }
 
 
 
    /*
 public void setUsers(Set<User> users) {
  this.users = users;
 }
    */
 
    /**
  * @return the displayHeader
  */
 public String getDisplayHeader() {
  return displayHeader;
 }

 /**
  * @param displayHeader the displayHeader to set
  */
 public void setDisplayHeader(String displayHeader) {
  this.displayHeader = displayHeader;
 }
 
 
 

 /**
  * @return the dateLastLogin
  */
 public Date getDateLastLogin() {
  return dateLastLogin;
 }

 /**
  * @param dateLastLogin the dateLastLogin to set
  */
 public void setDateLastLogin(Date dateLastLogin) {
  this.dateLastLogin = dateLastLogin;
 }

 /**
     * {@inheritDoc}
     */
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof User)) {
            return false;
        }

        final User user = (User) o;

        return !(username != null ? !username.equals(user.getUsername()) : user.getUsername() != null);

    }

    /**
     * {@inheritDoc}
     */
    public int hashCode() {
        return (username != null ? username.hashCode() : 0);
    }

    /**
     * {@inheritDoc}
     */
    public String toString() {
        ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
                .append("username", this.username)
                .append("enabled", this.enabled)
                .append("accountExpired", this.accountExpired)
                .append("credentialsExpired", this.credentialsExpired)
                .append("accountLocked", this.accountLocked);

        GrantedAuthority[] auths = this.getAuthorities();
        if (auths != null) {
            sb.append("Granted Authorities: ");

            for (int i = 0; i < auths.length; i++) {
                if (i > 0) {
                    sb.append(", ");
                }
                sb.append(auths[i].toString());
            }
        } else {
            sb.append("No Granted Authorities");
        }
        return sb.toString();
    }
    @Column(nullable=false)
 public boolean isNewsNotify() {
  return newsNotify;
 }

 public void setNewsNotify(boolean newsNotify) {
  this.newsNotify = newsNotify;
 }
 @Column(nullable=false)
 public boolean isCommentsNotify() {
  return commentsNotify;
 }

 public void setCommentsNotify(boolean commentsNotify) {
  this.commentsNotify = commentsNotify;
 }

 public boolean isFeaturedsEnabled() {
  return featuredsEnabled;
 }

 public void setFeaturedsEnabled(boolean featuredsEnabled) {
  this.featuredsEnabled = featuredsEnabled;
 }

 public void setToolTipFlagNotify(boolean toolTipFlagNotify) {
  this.toolTipFlagNotify = toolTipFlagNotify;
 }

}


 

生成user index 文件

 

 public void indexUser() {

  FullTextSession fullTextSession = Search.createFullTextSession(getSession());
  List<User> user = getSession()
  .createQuery("from User user where user.enabled=:enabled" )
  .setParameter("enabled", true)
  .list();
  for (User  tmpUser : user) {
   fullTextSession.index(tmpUser);
  }
 }

搜索:

 FullTextSession fullTextSession = Search.createFullTextSession(getSession());

  List<User> result=null;
  if(b){
   WildcardQuery   query=null;
   WildcardQuery   query2=null;
   WildcardQuery   query3=null;
   WildcardQuery   query4=null;
   WildcardQuery   query5=null;
   Term  term =null;
   Term term1 = null;
   Term term2 = null;
   Term term3 = null;
   Term term4 = null;
   term2=new Term("screenName",searchUser.toLowerCase());
   term3=new Term("screenName","*"+searchUser.toLowerCase());
   term4=new Term("screenName",searchUser.toLowerCase()+"*");
   term=new Term("screenName","*"+searchUser.toLowerCase()+"*");
   query=new WildcardQuery(term);
//   query2=new WildcardQuery(term1);
   query3=new WildcardQuery(term2);
   query4=new WildcardQuery(term3);
   query5=new WildcardQuery(term4);
  
         BooleanQuery bquery = new BooleanQuery();
         bquery.add(query, Occur.SHOULD);
         bquery.add(query3, Occur.SHOULD);
         bquery.add(query4, Occur.SHOULD);
         bquery.add(query5, Occur.SHOULD);
         FullTextQuery hibQuery =fullTextSession.createFullTextQuery(bquery,User.class);
         org.apache.lucene.search.Sort sort = new Sort(new SortField("screenName"));
         hibQuery.setSort(sort);
   scrollableResults=hibQuery.scroll();
   scrollableResults.last();
    if(scrollableResults.getRowNumber()>=0){
     totalResults=scrollableResults.getRowNumber() + 1;
    } else {
     totalResults=0;
   }
   hibQuery.setFirstResult((bean.getPageNumber()-1)*10);
   hibQuery.setMaxResults(10);

   System.out.println(totalResults+"=========================");
   bean.setElementCount(totalResults);
   int pageCount = (int) Math.ceil((new Integer(totalResults)
   .doubleValue())
   / (new Integer(bean.getPageSize()).doubleValue()));
   bean.setPageCount(pageCount);
   result = hibQuery.list();
   bean.setElements(result);

 

注:如果字段是index=Index.TOKENIZED 不能进行排序

 

Query query=null;
   QueryParser parser=null;
   parser =new QueryParser("screenName", new StandardAnalyzer());
   try{
    query= parser.parse(searchUser);
    FullTextQuery hibQuery = fullTextSession.createFullTextQuery(query,User.class);

          org.apache.lucene.search.Sort sort = new Sort(new SortField("screenName"));
          hibQuery.setSort(sort);
    scrollableResults=hibQuery.scroll();
    scrollableResults.last();
     if(scrollableResults.getRowNumber()>=0){
      totalResults=scrollableResults.getRowNumber() + 1;
     } else {
      totalResults=0;
    }
     hibQuery.setFirstResult((bean.getPageNumber()-1)*10);
     hibQuery.setMaxResults(10);
    System.out.println(totalResults+"=========================");
    bean.setElementCount(totalResults);
    int pageCount = (int) Math.ceil((new Integer(totalResults)
    .doubleValue())
    / (new Integer(bean.getPageSize()).doubleValue()));
    bean.setPageCount(pageCount);
    result = hibQuery.list();
    bean.setElements(result);

完成匹配才能查到.

 

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/h11h03/archive/2008/11/09/3261497.aspx

  评论这张
 
阅读(607)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017