In this tutorial, we will learn how to use Spring Boot with Spring data JPA to save data into an H2 in-memory database and how to also how to query the data.
package com.programmertoday.entities;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "Employee")
public class Employee implements Serializable {
private static final long serialVersionUID = -1798070786993154676L;
@Id
private Integer id;
@Column(name="name")
private String name;
@Column(name="address")
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3. Spring Data Repository
Create a Spring Data Repository Interface like below and go to the next step.
Here we created a Repository which Spring Data JPA has provided and extend a CrudRepository which provides us some boilerplate code and functionalities which helps us interact with the database just like a normal JPA or Hibernate would do.
2.> Also, Just For Testing Create two sample .sql scripts to create an Employee table and insert 2 records into that table on application load or startup.
Create 2 scripts as shown in the snapshot below:
Script.sql
Drop table if exists Employee;
Create table (id number , string name, string address);
Data.sql
insert into Employee (id,name,address) values (1,'John','US');
insert into Employee (id,name,address) values (2,'Mak','UK');
5. Run Main method – @SpringBootApplication
Now just open the main class and run it.
Voila !
Your SpringBoot Spring Data JPA application is up and running @ <localhost:port>
Default port will be 8080 [ example : localhost:8080 ]
When you run the main class of SpringBootApplication, you see the below log in the console which also tells you that the h2 in-memory data base is up and runnning at url “localhost:port/h2”
2020-01-26 21:11:55.948 INFO 22204 — [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at ‘/h2’. Database available at ‘jdbc:h2:mem:testdb’
Open h2 db : localhost:8080/h2
H2 DB URL : localhost:8080/h2H2 DB : Employee table created on spring boot application startup
Summary
In this tutorial, we learnt about Spring boot connectivity with H2 DB an in-memory database along with Spring DATA JPA as a JPA framework. We connected with H2 in-memory database to save/persist data into the database and it’s easy to test. Hope you liked it !
In this tutorial, we will learn how to use Spring Boot with Spring data JPA and Elastic Search to index data using elastic search and search data from the indexes.
Key Benefits from this :
We will make a REST API endpoint to index data into Elastic Search.
We will also make a REST API endpoint to search data using Elastic Search from the indexed data.
We will make a REST API to reindex the data.
We will make a REST API to delete all indexes of Elastic Search.
Create an entity called Employee.class – and annotate it also with @Document with index name and its type.
package com.test.sprinbootelastic.entities;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "Employee")
@Document(indexName = "employee", type = "employee",shards = 1)
public class Employee implements Serializable {
private static final long serialVersionUID = -1798070786993154676L;
@Id
private Integer id;
@Column(name="name")
private String name;
@Column(name="address")
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3. Spring Data Repository + Elastic Search Repository
Create a Spring Data Repository Interface like below and go to the next step.
Here we created a Repository which Spring Data JPA has provided and extend a CrudRepository which provides us some boilerplate code and functionalities which helps us interact with the database just like a normal JPA or Hibernate would do.
Create a class called ElasticSearchIndexer which helps in indexing Employee entity data which was stored in the h2 or any DB.
This class will be called from the controller.
package com.test.sprinbootelastic.util;
import com.test.sprinbootelastic.elasticrepo.EmpRepository;
import com.test.sprinbootelastic.entities.Employee;
import com.test.sprinbootelastic.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class ElasticSearchIndexer {
@Autowired
ElasticsearchOperations operations;
@Autowired
EmpRepository empRepository;
@Autowired
EmployeeRepository employeeRepository;
public void indexData(){
System.out.println("start data indexing**********");
operations.putMapping(Employee.class);
System.out.println("Loading Data Employee");
empRepository.save(getData());
System.out.printf("Loading Completed");
}
private Iterable<Employee> getData() {
List<Employee> list = new ArrayList<Employee>();
Iterable<Employee> emps = employeeRepository.findAll();
emps.forEach(list::add);
return emps;
}
}
7. Controller – Elastic Search REST End Points
REST API endpoints for elastic search.
package com.test.sprinbootelastic.controllers;
import com.test.sprinbootelastic.elasticrepo.EmpRepository;
import com.test.sprinbootelastic.entities.Employee;
import com.test.sprinbootelastic.repository.EmployeeRepository;
import com.test.sprinbootelastic.util.ElasticSearchIndexer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("api")
public class EmployeeController {
@Autowired
public EmployeeRepository employeeRepository;
@Autowired
public EmpRepository empRepository;
@Autowired
public ElasticSearchIndexer elasticSearchIndexer;
@GetMapping("/employee")
public Employee getEmployee() {
System.out.println("** This is spring boot application **");
Employee emp = new Employee();
emp = employeeRepository.findById(1);
System.out.println("employe :" + emp);
return emp;
}
/***** Elastic Search APIs *****/
@GetMapping(value = "/es/index")
public String indexEmployee() {
elasticSearchIndexer.indexData();
return "Data indexed Successfully";
}
@GetMapping(value = "/all")
public List<Employee> searchAll() {
List<Employee> usersList = new ArrayList<>();
Iterable<Employee> emps = empRepository.findAll();
emps.forEach(usersList::add);
return emps;
}
@GetMapping(value = "/es/deleteindexes")
public String deleteIndexes() {
empRepository.deleteAll();
return "Deleted all indexes";
}
}
8. Run Main method – @SpringBootApplication
Now just open the main class and run it.
Voila !
Your SpringBoot Spring Data JPA with Elastic Search application is up and running @ localhost:port
Default port will be 8080 [ example : localhost:8080 ]
You can hit the following Elastic Search REST end points like below:
localhost:8080/api/es/index : to create the indexed of the data present in db localhost:8080/api/all : to search entire Employee indexed data localhost:8080/api/deleteindexes : to delete all the indexes
Summary
In this tutorial, we learnt about Spring boot capabilities with Spring DATA Elastic Search which allows simple integration with elastic search, we created a few REST endpoints of elastic search to index and search the data. Hope you liked it !