Skip to content

Commit aadde5b

Browse files
authored
Merge pull request eugenp#3161 from markusgulden/master
BAEL-1336 Introduction to Hibernate Search
2 parents 9f54dea + d26adf6 commit aadde5b

6 files changed

Lines changed: 562 additions & 0 deletions

File tree

‎persistence-modules/spring-hibernate-5/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@
5757
<artifactId>jta</artifactId>
5858
<version>${jta.version}</version>
5959
</dependency>
60+
<dependency>
61+
<groupId>org.hibernate</groupId>
62+
<artifactId>hibernate-search-orm</artifactId>
63+
<version>${hibernatesearch.version}</version>
64+
</dependency>
6065

6166
<dependency>
6267
<groupId>org.apache.tomcat</groupId>
@@ -184,6 +189,7 @@
184189

185190
<!-- persistence -->
186191
<hibernate.version>5.2.10.Final</hibernate.version>
192+
<hibernatesearch.version>5.8.2.Final</hibernatesearch.version>
187193
<mysql-connector-java.version>8.0.7-dmr</mysql-connector-java.version>
188194
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
189195
<jta.version>1.1</jta.version>
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package com.baeldung.hibernatesearch;
2+
3+
import com.google.common.base.Preconditions;
4+
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.ComponentScan;
8+
import org.springframework.context.annotation.Configuration;
9+
import org.springframework.context.annotation.PropertySource;
10+
import org.springframework.core.env.Environment;
11+
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
12+
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
13+
import org.springframework.jdbc.datasource.DriverManagerDataSource;
14+
import org.springframework.orm.jpa.JpaTransactionManager;
15+
import org.springframework.orm.jpa.JpaVendorAdapter;
16+
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
17+
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
18+
import org.springframework.transaction.PlatformTransactionManager;
19+
import org.springframework.transaction.annotation.EnableTransactionManagement;
20+
21+
import javax.persistence.EntityManagerFactory;
22+
import javax.sql.DataSource;
23+
import java.util.Properties;
24+
25+
@EnableTransactionManagement
26+
@Configuration
27+
@PropertySource({ "classpath:persistence-h2.properties" })
28+
@EnableJpaRepositories(basePackages = { "com.baeldung.hibernatesearch" })
29+
@ComponentScan({ "com.baeldung.hibernatesearch" })
30+
public class HibernateSearchConfig {
31+
32+
@Autowired
33+
private Environment env;
34+
35+
@Bean
36+
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
37+
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
38+
em.setDataSource(dataSource());
39+
em.setPackagesToScan(new String[] { "com.baeldung.hibernatesearch.model" });
40+
41+
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
42+
em.setJpaVendorAdapter(vendorAdapter);
43+
em.setJpaProperties(additionalProperties());
44+
45+
return em;
46+
}
47+
48+
@Bean
49+
public DataSource dataSource() {
50+
final BasicDataSource dataSource = new BasicDataSource();
51+
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
52+
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
53+
54+
return dataSource;
55+
}
56+
57+
@Bean
58+
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
59+
JpaTransactionManager transactionManager = new JpaTransactionManager();
60+
transactionManager.setEntityManagerFactory(emf);
61+
62+
return transactionManager;
63+
}
64+
65+
@Bean
66+
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
67+
return new PersistenceExceptionTranslationPostProcessor();
68+
}
69+
70+
Properties additionalProperties() {
71+
Properties properties = new Properties();
72+
properties.setProperty("hibernate.hbm2ddl.auto", Preconditions.checkNotNull(env.getProperty("hibernate.hbm2ddl.auto")));
73+
properties.setProperty("hibernate.dialect", Preconditions.checkNotNull(env.getProperty("hibernate.dialect")));
74+
return properties;
75+
}
76+
}
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
package com.baeldung.hibernatesearch;
2+
3+
import com.baeldung.hibernatesearch.model.Product;
4+
import org.apache.lucene.search.Query;
5+
import org.hibernate.search.engine.ProjectionConstants;
6+
import org.hibernate.search.jpa.FullTextEntityManager;
7+
import org.hibernate.search.jpa.FullTextQuery;
8+
import org.hibernate.search.jpa.Search;
9+
import org.hibernate.search.query.dsl.QueryBuilder;
10+
import org.springframework.stereotype.Repository;
11+
12+
import javax.persistence.EntityManager;
13+
import javax.persistence.PersistenceContext;
14+
import java.util.List;
15+
16+
@Repository
17+
public class ProductSearchDao {
18+
19+
@PersistenceContext
20+
private EntityManager entityManager;
21+
22+
public List<Product> searchProductNameByKeywordQuery(String text) {
23+
24+
Query keywordQuery = getQueryBuilder()
25+
.keyword()
26+
.onField("productName")
27+
.matching(text)
28+
.createQuery();
29+
30+
List<Product> results = getJpaQuery(keywordQuery).getResultList();
31+
32+
return results;
33+
}
34+
35+
public List<Product> searchProductNameByFuzzyQuery(String text) {
36+
37+
Query fuzzyQuery = getQueryBuilder()
38+
.keyword()
39+
.fuzzy()
40+
.withEditDistanceUpTo(2)
41+
.withPrefixLength(0)
42+
.onField("productName")
43+
.matching(text)
44+
.createQuery();
45+
46+
List<Product> results = getJpaQuery(fuzzyQuery).getResultList();
47+
48+
return results;
49+
}
50+
51+
public List<Product> searchProductNameByWildcardQuery(String text) {
52+
53+
Query wildcardQuery = getQueryBuilder()
54+
.keyword()
55+
.wildcard()
56+
.onField("productName")
57+
.matching(text)
58+
.createQuery();
59+
60+
List<Product> results = getJpaQuery(wildcardQuery).getResultList();
61+
62+
return results;
63+
}
64+
65+
public List<Product> searchProductDescriptionByPhraseQuery(String text) {
66+
67+
Query phraseQuery = getQueryBuilder()
68+
.phrase()
69+
.withSlop(1)
70+
.onField("description")
71+
.sentence(text)
72+
.createQuery();
73+
74+
List<Product> results = getJpaQuery(phraseQuery).getResultList();
75+
76+
return results;
77+
}
78+
79+
public List<Product> searchProductNameAndDescriptionBySimpleQueryStringQuery(String text) {
80+
81+
Query simpleQueryStringQuery = getQueryBuilder()
82+
.simpleQueryString()
83+
.onFields("productName", "description")
84+
.matching(text)
85+
.createQuery();
86+
87+
List<Product> results = getJpaQuery(simpleQueryStringQuery).getResultList();
88+
89+
return results;
90+
}
91+
92+
public List<Product> searchProductNameByRangeQuery(int low, int high) {
93+
94+
Query rangeQuery = getQueryBuilder()
95+
.range()
96+
.onField("memory")
97+
.from(low)
98+
.to(high)
99+
.createQuery();
100+
101+
List<Product> results = getJpaQuery(rangeQuery).getResultList();
102+
103+
return results;
104+
}
105+
106+
public List<Object[]> searchProductNameByMoreLikeThisQuery(Product entity) {
107+
108+
Query moreLikeThisQuery = getQueryBuilder()
109+
.moreLikeThis()
110+
.comparingField("productName")
111+
.toEntity(entity)
112+
.createQuery();
113+
114+
List<Object[]> results = getJpaQuery(moreLikeThisQuery).setProjection(ProjectionConstants.THIS, ProjectionConstants.SCORE)
115+
.getResultList();
116+
117+
return results;
118+
}
119+
120+
public List<Product> searchProductNameAndDescriptionByKeywordQuery(String text) {
121+
122+
Query keywordQuery = getQueryBuilder()
123+
.keyword()
124+
.onFields("productName", "description")
125+
.matching(text)
126+
.createQuery();
127+
128+
List<Product> results = getJpaQuery(keywordQuery).getResultList();
129+
130+
return results;
131+
}
132+
133+
public List<Object[]> searchProductNameAndDescriptionByMoreLikeThisQuery(Product entity) {
134+
135+
Query moreLikeThisQuery = getQueryBuilder()
136+
.moreLikeThis()
137+
.comparingField("productName")
138+
.toEntity(entity)
139+
.createQuery();
140+
141+
List<Object[]> results = getJpaQuery(moreLikeThisQuery).setProjection(ProjectionConstants.THIS, ProjectionConstants.SCORE)
142+
.getResultList();
143+
144+
return results;
145+
}
146+
147+
public List<Product> searchProductNameAndDescriptionByCombinedQuery(String manufactorer, int memoryLow, int memoryTop, String extraFeature, String exclude) {
148+
149+
Query combinedQuery = getQueryBuilder()
150+
.bool()
151+
.must(getQueryBuilder().keyword()
152+
.onField("productName")
153+
.matching(manufactorer)
154+
.createQuery())
155+
.must(getQueryBuilder()
156+
.range()
157+
.onField("memory")
158+
.from(memoryLow)
159+
.to(memoryTop)
160+
.createQuery())
161+
.should(getQueryBuilder()
162+
.phrase()
163+
.onField("description")
164+
.sentence(extraFeature)
165+
.createQuery())
166+
.must(getQueryBuilder()
167+
.keyword()
168+
.onField("productName")
169+
.matching(exclude)
170+
.createQuery())
171+
.not()
172+
.createQuery();
173+
174+
List<Product> results = getJpaQuery(combinedQuery).getResultList();
175+
176+
return results;
177+
}
178+
179+
private FullTextQuery getJpaQuery(org.apache.lucene.search.Query luceneQuery) {
180+
181+
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
182+
183+
return fullTextEntityManager.createFullTextQuery(luceneQuery, Product.class);
184+
}
185+
186+
private QueryBuilder getQueryBuilder() {
187+
188+
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
189+
190+
return fullTextEntityManager.getSearchFactory()
191+
.buildQueryBuilder()
192+
.forEntity(Product.class)
193+
.get();
194+
}
195+
}
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package com.baeldung.hibernatesearch.model;
2+
3+
import org.hibernate.search.annotations.*;
4+
5+
import javax.persistence.Entity;
6+
import javax.persistence.Id;
7+
import javax.persistence.Table;
8+
9+
@Entity
10+
@Indexed
11+
@Table(name = "product")
12+
public class Product {
13+
14+
@Id
15+
private int id;
16+
17+
@Field(termVector = TermVector.YES)
18+
private String productName;
19+
20+
@Field(termVector = TermVector.YES)
21+
private String description;
22+
23+
@Field
24+
private int memory;
25+
26+
public Product(int id, String productName, int memory, String description) {
27+
this.id = id;
28+
this.productName = productName;
29+
this.memory = memory;
30+
this.description = description;
31+
}
32+
33+
public Product() {
34+
}
35+
36+
@Override
37+
public boolean equals(Object o) {
38+
if (this == o)
39+
return true;
40+
if (!(o instanceof Product))
41+
return false;
42+
43+
Product product = (Product) o;
44+
45+
if (id != product.id)
46+
return false;
47+
if (memory != product.memory)
48+
return false;
49+
if (!productName.equals(product.productName))
50+
return false;
51+
return description.equals(product.description);
52+
}
53+
54+
@Override
55+
public int hashCode() {
56+
int result = id;
57+
result = 31 * result + productName.hashCode();
58+
result = 31 * result + memory;
59+
result = 31 * result + description.hashCode();
60+
return result;
61+
}
62+
63+
public int getId() {
64+
return id;
65+
}
66+
67+
public void setId(int id) {
68+
this.id = id;
69+
}
70+
71+
public String getProductName() {
72+
return productName;
73+
}
74+
75+
public void setProductName(String productName) {
76+
this.productName = productName;
77+
}
78+
79+
public int getMemory() {
80+
return memory;
81+
}
82+
83+
public void setMemory(int memory) {
84+
this.memory = memory;
85+
}
86+
87+
public String getDescription() {
88+
return description;
89+
}
90+
91+
public void setDescription(String description) {
92+
this.description = description;
93+
}
94+
}

‎persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,9 @@ hibernate.dialect=org.hibernate.dialect.H2Dialect
99
hibernate.show_sql=false
1010
hibernate.hbm2ddl.auto=create-drop
1111

12+
# hibernate.search.X
13+
hibernate.search.default.directory_provider = filesystem
14+
hibernate.search.default.indexBase = /data/index/default
15+
1216
# envers.X
1317
envers.audit_table_suffix=_audit_log

0 commit comments

Comments
 (0)