简体   繁体   English

如何使用Spring Boot在Spring MVC中实现高级搜索功能?

[英]How to implement advanced search functionality in Spring MVC with Spring Boot?

I am new to Spring Boot. 我是Spring Boot的新手。 I am implementing the microservices architecture. 我正在实现微服务架构。 I have two entities driver and car. 我有两个实体驾驶员和汽车。 There is one to one relationship between driver and car. 驾驶员与汽车之间存在一对一的关系。 One driver can select only one car and one car can be selected by only one driver. 一位驾驶员只能选择一辆汽车,而一位驾驶员只能选择一辆汽车。

I want to implement advanced search functionality. 我想实现高级搜索功能。 It should be possible to search for drivers by their attributes (username, online_status) as well as car characteristics (license number, car name, etc). 应该可以通过驾驶员的属性(用户名,online_status)以及汽车特性(驾照编号,汽车名称等)来搜索驾驶员。 I am using Database as H2 (In memory). 我正在将数据库用作H2(在内存中)。 I want to avoid nested if and else. 我要避免嵌套if和else。

What is the best way to do this in Spring Boot? 在Spring Boot中执行此操作的最佳方法是什么?

I think the best way to do it is enable hibernate-search module in your code. 我认为最好的方法是在代码中启用hibernate-search模块。 For this aim you could use Indexed and Field annotation. 为此,您可以使用索引和字段注释。

example below 下面的例子

@Entity
@Indexed
public class Car {
    @Column(name = "name")
    @Field
    private String name;

    @Column(name = "license_number")
    @Field
    private Integer licenseNumber;


}

And after that you could use search functionality in your service layer 之后,您可以在服务层中使用搜索功能

@Service
public class CarServiceImpl implements CarService {

    @PersistenceContext
    private EntityManager entityManager;

@Override
    @Transactional
    public List<Car> search(Sting name, String licenseNumber) {
        FullTextSearchBuilder builder = new FullTextSearchBuilder(entityManager, Car.class);
        builder.appendAndQuery(name, "name");
        builder.appendAndQuery(licenseNumber, "licenseNumber");
        FullTextQuery fullTextQuery = builder.createFullTextQuery();
        return (List<Car>) fullTextQuery.getResultList();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM