4

我正在尝试将休眠搜索集成到我的项目中。我的模型已编入索引,但由于某种原因,我的搜索查询没有返回任何结果。我已经尝试解决这个问题几个小时了,但我所做的似乎没有任何效果。

域对象:

@Entity
@Table(name = "roles")
@Indexed
public class Role implements GrantedAuthority {
private static final long serialVersionUID = 8227887773948216849L;

    @Id @GeneratedValue
    @DocumentId
    private Long ID;

    @Column(name = "authority", nullable = false)
    @Field(index = Index.TOKENIZED, store = Store.YES)
    private String authority;

    @ManyToMany
    @JoinTable(name = "user_roles", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "username") })
    @ContainedIn
    private List<User> users;

    ...

}

道:

public abstract class GenericPersistenceDao<T> implements IGenericDao<T> {

@PersistenceContext
private EntityManager entityManager;

...

    @Override
    public FullTextEntityManager getSearchManager() {
        return Search.getFullTextEntityManager(entityManager);
    }

}

服务:

@Service(value = "roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDAO;

    ...

    @Override
    @SuppressWarnings("unchecked")
    public List<Role> searchRoles(String keyword) throws ParseException {
        FullTextEntityManager manager = roleDAO.getSearchManager();
        TermQuery tquery = new TermQuery(new Term("authority", keyword));
        FullTextQuery query = manager.createFullTextQuery(tquery, Role.class);
        return query.getResultList();
    }

}

测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@Transactional
public class TestRoleService extends Assert {

    @Autowired
    private RoleService roleService;

    @Test
    public void testSearchRoles() {
       roleService.saveRole(/* role with authority="test" */);
       List<Role> roles = roleService.searchRoles("test");
       assertEquals(1, roles.size()); // returns 0
    }

}

配置

<persistence-unit name="hibernatePersistence" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.search.default.directory_provider" value="org.hibernate.search.store.FSDirectoryProvider" />
            <property name="hibernate.search.default.indexBase" value="indexes" />
        </properties>
</persistence-unit>

<!-- Entity manager -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="hibernatePersistence" />
</bean>

<!-- Transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<!-- Enable the configuration of transaction behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />

<context:component-scan base-package="org.myproject" />

数据库实际上填充了与该权限字段值匹配的角色。实体管理器是有效的,因为我所有的常规 CRUD 测试都成功了。这意味着该错误完全与休眠搜索(3.1.1.GA)相关,但它哪里出错了?

4

3 回答 3

2

理论上一切正常,但可能存在一些问题:

  • 您最初是否为现有对象编制索引?虽然 Hibernate Search 索引所有新更改,但它不知道预先存在的对象,因此您需要最初索引它们(使用 ftem#index())
  • 默认情况下,HSearch 挂钩到 Hibernate 或 JTA 事务以侦听事务事件之前和之后。也许您的 Spring tx 配置绕过了它,因此 HSearch 没有被触发,因此无法索引。最好的方法确实是使用真正的 JTA 事务管理器并避免这些外观。
  • 如果您正在谈论初始索引(使用 index()),您也可以使用 #flushToIndexes() 强制索引,即使未提交 tx 也是如此。
  • 最后但并非最不重要的一点是,您的最后一段代码可能会抛出 OutOfMemoryException,因为您在索引它们之前将所有对象加载到内存中。查看 Hibernate Search 参考文档,了解如何正确索引批量对象负载。Manning(我是作者)的 Hibernate Search in Action 也更深入地研究了这一切。
于 2009-12-22T10:42:55.347 回答
1

Finally managed getting it to work.. apparently the objects are not automatically indexed.. or not committed at least. My implementation now looks as follows:

public List<Role> searchRoles(String keyword) {
        // Index domain object (works)
        EntityManager manager = factory.createEntityManager();
        FullTextEntityManager ftManager = Search.getFullTextEntityManager(manager);
        ftManager.getTransaction().begin();

        List<Role> roles = ftManager.createQuery("select e from " + Role.class.getName() + " e").getResultList();
        for (Role role : roles) {
            ftManager.index(role);
        }
        ftManager.getTransaction().commit();

        // Retrieve element from search (works)
        TermQuery tquery = new TermQuery(new Term("authority", keyword));
        FullTextQuery query = ftManager.createFullTextQuery(tquery, Role.class);
        return query.getResultList();
}

By performing the index and getTransactionCommit functions the indexes are correctly stored in my indexes folder. This implementation, however, is pretty unnatural as I make an alternative entity manager for text searching. Is there a "cleaner" way to index( and commit ) records using the @Transactional annotations???

于 2009-12-21T15:05:29.730 回答
1

最终通过附加以下属性解决了我的问题:hibernate.search.worker.batch_size=1

我现在不仅可以正确查询,而且只要我持久化我的域对象,索引也会自动更新。我现在唯一遇到的问题是通过我的 import.sql 插入的数据没有自动索引。是否有某种“神奇”的 hibernate.search 属性可用于此问题,或者我应该手动索引它们?

于 2009-12-23T12:13:39.407 回答