FK的休眠全文搜索

时间:2019-01-16 15:29:34

标签: java hibernate lucene

我正在尝试通过搜索模式查找属于给定国家的邮政编码。

搜索方法:

public Stream<ZIP> search(final String pattern, final Long countryId) {
        if (pattern == null) {
            return repository.findAll().stream();
        }

        @Cleanup FullTextEntityManager manager = factory.get();
        final QueryBuilder qb = manager.getSearchFactory().buildQueryBuilder().forEntity(ZIP.class).get();
        Query query;
        if (countryId == null) {
            query = qb.keyword().wildcard().onField(ZIP_.zip.getName()).matching(pattern.toLowerCase() + "*").createQuery();
        } else {
            query = qb.bool()
              .must(qb.keyword().wildcard().onField(ZIP_.zip.getName()).matching(pattern.toLowerCase() + "*").createQuery())
              .must(qb.keyword().wildcard().onField(ZIP_.country.getName() + "." + Country_.id.getName()).matching(countryId).createQuery())
                    .createQuery();
        }

        return manager.createFullTextQuery(query, ZIP.class).getResultList().stream();
    }

这是我的Entity类:

@EqualsAndHashCode(callSuper = true)
@Entity
@Data
@Table(name = "zips")
@Indexed
public class ZIP extends TableBased {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    @Field(store = Store.YES)
    @Analyzer(definition = "textAnalyzer")
    private String zip;

    @ManyToOne(cascade = ALL, fetch = LAZY)
    @JoinColumn(name = "country", nullable = false)
    @IndexedEmbedded(includeEmbeddedObjectId = true, depth = 0)
    private Country country;

    @OneToMany(mappedBy = "zip")
    private List<Address> addresses;
}

@EqualsAndHashCode(callSuper = true) 
@Entity
@Indexed
@Data
@Table(name = "countries")
public class Country extends TableBased {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    @Field(store = Store.YES)
    @Analyzer(definition = "textAnalyzer")
    private String name;

    @OneToMany(mappedBy = "country")
    private List<Province> provinces;

    @OneToMany(mappedBy = "country")
    private List<ZIP> zips;

    @OneToMany(mappedBy = "country")
    private List<Address> addresses;

    @OneToOne(fetch = LAZY, mappedBy = "country")
    private BaseLocation baseLocation;
}

在另一个用例中,也会单独搜索国家(地区)实体,因此其@Indexed也是如此。 每当countryId为null时,一切都会按预期工作,但是给定的ID只要该方法始终返回空流,即使数据库中确实存在相应的数据也是如此。你们有什么主意吗?

0 个答案:

没有答案