Spring Boot + Hibernate Search示例

在这里,我们将使用Hibernate Search + Thymeleaf模板引擎创建一个Spring Boot Web应用程序示例,并将其作为WAR部署到Wildfly 10.1。

使用的技术:

  1. Spring Boot 1.5.6。发布
  2. Java 8
  3. Hibernate Search 5.6.1。最终版
  4. 嵌入式Tomcat,Wildfly 8.1 Final和10.1 Final

1.项目结构

标准的Maven项目结构

1.项目依赖

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
	http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mkyong</groupId>
    <artifactId>spring-boot-web-wildfly-search</artifactId>
    <version>0.0.1</version>
    <packaging>war</packaging>
    <name>mkyong-wildfly-spring-boot</name>
    <description>Spring Boot Web Hibernate Search Example</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <logback.version>1.1.9</logback.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--
            Comment out if deploy as WAR file
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
            -->
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-search-engine -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-engine</artifactId>
            <version>5.6.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jboss.logging</groupId>
                    <artifactId>jboss-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-search-orm -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-orm</artifactId>
            <version>5.6.1.Final</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jboss.logging</groupId>
                    <artifactId>jboss-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.0.Final</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.1.9</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <layout>WAR</layout>
                    <executable>true</executable>
                    <mainClass>com.mkyong.WildflySpringBootApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2.型号

对于此示例应用程序,我们正在创建一个网站,使您可以搜索稀有的棒球卡。 因此,我们将模型制作为棒球卡并注释什么是可搜索字段。

BaseballCard.java
package com.mkyong.model;

import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Indexed
@Entity
public class BaseballCard {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Field
    private String name;
    @Field
    private String rarityLevel;
    @Field
    private int year;
	
    //getters n setters

}

3.储存库

在这里,我们为BaseballCard模型提供了一个Spring Data CrudRepository ,它将使我们能够执行所需的创建和读取功能。

BaseballCardRepository.java
package com.mkyong.dao;

import org.springframework.data.repository.CrudRepository;

import com.mkyong.model.BaseballCard;

public interface BaseballCardRepository extends CrudRepository<BaseballCard,Long> {
}

4.休眠搜索

HibernateSearchService.java
package com.mkyong.service;

import com.mkyong.model.BaseballCard;
import org.apache.lucene.search.Query;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import java.util.List;

@Service
public class HibernateSearchService {


    @Autowired
    private final EntityManager centityManager;


    @Autowired
    public HibernateSearchService(EntityManager entityManager) {
        super();
        this.centityManager = entityManager;
    }


    public void initializeHibernateSearch() {

        try {
            FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(centityManager);
            fullTextEntityManager.createIndexer().startAndWait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public List<BaseballCard> fuzzySearch(String searchTerm) {

        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(centityManager);
        QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(BaseballCard.class).get();
        Query luceneQuery = qb.keyword().fuzzy().withEditDistanceUpTo(1).withPrefixLength(1).onFields("name")
                .matching(searchTerm).createQuery();

        javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(luceneQuery, BaseballCard.class);

        // execute search

        List<BaseballCard> BaseballCardList = null;
        try {
            BaseballCardList = jpaQuery.getResultList();
        } catch (NoResultException nre) {
            ;// do nothing

        }

        return BaseballCardList;


    }
}

HibernateSearchService配置为可访问。

HibernateSearchConfiguration.java
package com.mkyong;

import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mkyong.service.HibernateSearchService;
@EnableAutoConfiguration 
@Configuration
public class HibernateSearchConfiguration {

	@Autowired
	private EntityManager bentityManager;

	@Bean
	HibernateSearchService hibernateSearchService() {
		HibernateSearchService hibernateSearchService = new HibernateSearchService(bentityManager);
		hibernateSearchService.initializeHibernateSearch();
		return hibernateSearchService;
	}
}

5.模型服务

这是一项简单的服务,为我们的示例在存储库中添加了三张卡片。 为了演示SOLID编程原理,该服务有单独的接口。

CardService.java
package com.mkyong.service;

public interface CardService {

    void addCards();
    
}
CardServiceImpl.java
package com.mkyong.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mkyong.dao.BaseballCardRepository;
import com.mkyong.model.BaseballCard;

@Service
public class CardServiceImpl implements CardService {

    @Autowired
    BaseballCardRepository cardrepository;

    BaseballCard TedWilliams = new BaseballCard();
    BaseballCard BobGibson = new BaseballCard();
    BaseballCard HonusWagner = new BaseballCard();

    public void addCards() {
        TedWilliams.setName("Ted Williams");
        TedWilliams.setYear(1954);
        TedWilliams.setRarityLevel("Very Rare");

        cardrepository.save(TedWilliams);

        BobGibson.setName("Bob Gibson");
        BobGibson.setYear(1959);
        BobGibson.setRarityLevel("Very Rare");

        cardrepository.save(BobGibson);

        HonusWagner.setName("Honus Wagner");
        HonusWagner.setYear(1909);
        HonusWagner.setRarityLevel("Rarest");

        cardrepository.save(HonusWagner);

        System.out.println("Cards have been added : " + cardrepository.findAll());

    }
}

6.控制器

控制器负责将后端服务连接到我们的前端Thymeleaf模板。

CardController.java
package com.mkyong.controller;

import com.mkyong.model.BaseballCard;
import com.mkyong.service.CardService;
import com.mkyong.service.HibernateSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class CardController {

    @Autowired
    private HibernateSearchService searchservice;

    @Autowired
    private CardService cardservice;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String search(@RequestParam(value = "search", required = false) String q, Model model) {
        List<BaseballCard> searchResults = null;
        try {
            cardservice.addCards();
            searchResults = searchservice.fuzzySearch(q);

        } catch (Exception ex) {
            // here you should handle unexpected errors
            // ...
            // throw ex;
        }
        model.addAttribute("search", searchResults);
        return "index";

    }

}

7.配置

现在,我们需要配置Thymeleaf和Hibernate Search。

application.properties
#==================================
# = Thymeleaf configurations 
#==================================
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
server.contextPath=/
#===================================
#= 
# Specify the Lucene Directory
spring.jpa.properties.hibernate.search.default.directory_provider = filesystem

# Using the filesystem DirectoryProvider you also have to specify the default
# base directory for all indexes 
spring.jpa.properties.hibernate.search.default.indexBase = indexpath

8. Thymeleaf模板

对于我们的Thymeleaf模板,我们有两个目的:允许用户搜索并在搜索完成后显示搜索结果。 值得庆幸的是,Thymeleaf具有条件语句,如果用户的搜索返回了项目,这些条件语句使我们可以显示结果。

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- META SECTION -->
    <title>Mkyong Wildfly Example</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <!-- END META SECTION -->
    <!--  BEGIN STYLE -->
    <style>
        table, th, td {
            border: 1px solid black;
            padding: 1px;
        }
    </style>
    <!--  END STYLE -->

</head>
<body>
<form action="#" th:action="@{/}" th:object="${search}">
    <label for="search_input">Search:</label> <input name="search"
                                                     id="search">
    </input>
    <div th:if="${not #lists.isEmpty(search)}">
        <h2>Search Results</h2>
        <table>
            <thead>
            <tr>
                <th>ID</th>
                <th>name</th>
                <th>rarity level</th>
                <th>year</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="search : ${search}">
                <td th:text="${search.id}">Text ...</td>
                <td th:text="${search.name}">Text ...</td>
                <td th:text="${search.rarityLevel}">Text ...</td>
                <td th:text="${search.year}">Text...</td>
            </tr>
            </tbody>
        </table>
    </div>
</form>
</body>
</html>

9. SpringBootApplication

WildflySpringBootApplication.java
package com.mkyong;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WildflySpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(WildflySpringBootApplication.class, args);
    }

}

10.演示

使用默认的嵌入式Tomcat容器启动Spring Boot Application。

$ mvn spring-boot:run

访问http:// localhost:8080 /

我搜索了“ Ted”,结果显示在表http:// localhost:8080 /?search = ted中

11.将WAR文件部署到Wildfly

Wildfly是JBoss开源应用服务器。 可以从其官方网站下载Wildfly

Wildfly 10随附:
ActiveMQ Artemis,HA Singleton部署,HA Singleton消息驱动的Bean(MDB)和MDB传递组,无状态会话Bean和消息驱动的Bean自动池大小调整,Hibernate 5

Wildfly 8和9:
这些版本不具有Wildfly 10内置的技术。 这意味着我们将不需要在其配置文件中进行排除。

11.1排除嵌入式Tomcat容器。

pom.xml
<dependency>
           <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

11.2扩展SpringBootServletInitializer

WildflySpringBootApplication.java
package com.mkyong;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class WildflySpringBootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(WildflySpringBootApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(WildflySpringBootApplication.class, args);
    }

}

11.3 Maven构建并将WAR文件复制到JBoss Wildfly并启动它。

Terminal
$ mvn package

11.4 Wildfly 10的注意事项

对于Wildfly 10,我们需要进行其他更改,因为它附带了预包装的技术。 在我们的例子中,我们使用的是Hibernate Search,它包装在Wildfly 10中。

对于Wildfly 10的用户,您需要创建一个persistence.xml文件并输入:

persistence.xml
wildfly.jpa.hibernate.search.module = none

做完了

下载源代码

下载它– spring-boot-hibernate-search-example.zip (24 KB)

参考文献

  1. Hibernate Search 5.6文档
  2. 部署Spring Boot应用程序
  3. 胸腺+春天
  4. Spring Boot –将WAR文件部署到Tomcat

翻译自: https://mkyong.com/spring-boot/spring-boot-hibernate-search-example/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里提供一个基于 Spring Boot 和 Vue3 的示例项目,可以作为参考: 后端 Spring Boot 部分: 1. 创建一个 Spring Boot 项目,添加以下依赖: ``` <dependencies> <!-- Spring Boot Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- H2 Database --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <!-- Spring Boot Test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> ``` 2. 在 `application.properties` 文件中配置数据库连接: ``` spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.hibernate.ddl-auto=update ``` 3. 创建一个实体类 `User`: ``` @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; // getters and setters omitted for brevity } ``` 4. 创建一个 `UserRepository` 接口: ``` public interface UserRepository extends JpaRepository<User, Long> { User findByUsername(String username); } ``` 5. 创建一个 `UserController` 类,处理用户相关的请求: ``` @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/{username}") public User getUserByUsername(@PathVariable String username) { return userRepository.findByUsername(username); } @PostMapping("/") public User createUser(@RequestBody User user) { return userRepository.save(user); } } ``` 前端 Vue3 部分: 1. 安装 Vue CLI: ``` npm install -g @vue/cli ``` 2. 创建一个 Vue3 项目: ``` vue create my-project ``` 3. 安装 axios: ``` npm install axios ``` 4. 在 `src/main.js` 文件中添加以下代码: ``` import { createApp } from 'vue' import App from './App.vue' import axios from 'axios' axios.defaults.baseURL = 'http://localhost:8080/api' const app = createApp(App) app.config.globalProperties.$http = axios app.mount('#app') ``` 5. 创建一个 `Users.vue` 组件,显示用户列表: ``` <template> <div> <h1>Users</h1> <ul> <li v-for="user in users" :key="user.id"> {{ user.username }} </li> </ul> </div> </template> <script> export default { data() { return { users: [] } }, mounted() { this.$http.get('/users').then(response => { this.users = response.data }) } } </script> ``` 6. 在 `App.vue` 中添加一个路由: ``` <template> <div> <router-view /> </div> </template> <script> import { createRouter, createWebHashHistory } from 'vue-router' import Users from './Users.vue' const routes = [ { path: '/', component: Users } ] const router = createRouter({ history: createWebHashHistory(), routes }) export default { router } </script> ``` 这样,我们就完成了一个基于 Spring Boot 和 Vue3 的示例项目,可以通过 `npm run serve` 命令启动前端应用,通过 `mvn spring-boot:run` 命令启动后端应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值