Required Tools:
Spring Initializr
IDE
Spring Boot CLI tool.
We are using the Spring Initializr for this blog. As part of the setup, we will add, Web, JPA, MySQL dependencies our application. To start, go to the Spring Initializr and create the project structure.
Click on the “Generate” button to download the project structure on your machine.
Unzip the downloaded file and import it to your IDE
There is a file called pom.xml which should look like below
Spring Boot will automatically try to create DataSource if it finds the if spring-data-jpa is in the class-path. It will try to read the database configurations from the application.properties file.
Let’s add the database configuration to our application.properties file and let Spring Boot to do the rest of work for us.
#datasource configurationsspring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-hibernate?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # DDL generationspring.jpa.generate-ddl=true
To use the hibernate to work with our data, let’s create a customer entity to store and retrieve customer information from the database.
@EntitypublicclassCustomer{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
publicCustomer(){ } //get & set methods }
Let’s cover some important points from our entity class:
The @Entity annotation show that this class is an entity class.
We are not using @Table annotation, Hibernate will map it to the table named as “Customer“. You can use a different table name with <span class="token annotation punctuation">@Table</span><span class="token punctuation">(</span>name <span class="token operator">=</span> <span class="token string">"User"</span><span class="token punctuation">)</span>
The @Id annotation mark the id field as unique id field. We are using the identity generation strategy for our example.
The firstName and lastName are un-mapped and it will map them to the same column name as in the properties. We have the option to use @Column annotation to customize column names.
Spring JPA provide a transparent integration with the underlying JPA layer using the JPA repositories. It will take care of creating repository implementations automatically, at run-time, from a repository interface. Let’s create a simple CustomerRepository for our Customer entity and let Spring JPA handle the implementation part for us:
import com.javadevjournal.data.Customer; import org.springframework.data.repository.CrudRepository; @RepositorypublicinterfaceCustomerRepositoryextendsJpaRepository<Customer,Long> { }
Spring JPA handle most of the work for us and we only need to define the interface.The @Repository annotation helps Spring to bootstrap the JPA features during component scanning
Let’s create a simple service which will interact with the JPA repository to perform database operations:
package com.javadevjournal.service;
import com.javadevjournal.data.Customer;
import com.javadevjournal.dto.CustomerData;
import com.javadevjournal.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
import java.util.ArrayList;
import java.util.List;
@Service("customerService")
publicclassDefaultCustomerServiceimplementsCustomerService{ @Autowired
private CustomerRepository customerRepository;
@Override
public CustomerData saveCustomer(CustomerData customer){
Customer customerModel = populateCustomerEntity(customer);
return populateCustomerData(customerRepository.save(customerModel));}
@Override
public boolean deleteCustomer(Long customerId)
{
customerRepository.deleteById(customerId);
return true;
}
@Override
public List < CustomerData > getAllCustomers() {
List < CustomerData > customers = new ArrayList < > ();
List < Customer > customerList = customerRepository.findAll(); customerList.forEach(customer - > { customers.add(populateCustomerData(customer)); });
return customers; }
@Override
public CustomerData getCustomerById(Long customerId){
return populateCustomerData(customerRepository.findById(customerId).orElseThrow(() - > new EntityNotFoundException("Customer not found"))); }
private CustomerData populateCustomerData(final Customer customer)
{
CustomerData customerData = new CustomerData(); customerData.setId(customer.getId()); customerData.setFirstName(customer.getFirstName()); customerData.setLastName(customer.getLastName()); customerData.setEmail(customer.getEmail());
return customerData; }
private Customer populateCustomerEntity(CustomerData customerData){ Customer customer = new Customer(); customer.setFirstName(customerData.getFirstName()); customer.setLastName(customerData.getLastName()); customer.setEmail(customerData.getEmail());
return customer; } }
Our service class provides method to save, delete and find all customers in the database.
Let's create a controller for customer class
package com.javadevjournal.controller;
import com.javadevjournal.dto.CustomerData;
import com.javadevjournal.service.CustomerService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController@RequestMapping("/customers")public class CustomerController {
@Resource(name = "customerService")private CustomerService customerService;
@GetMappingpublic List < CustomerData > getCustomers() {
return customerService.getAllCustomers();
}
@GetMapping("/customer/{id}")public CustomerData getCustomer(@PathVariable Long id) {
return customerService.getCustomerById(id);
}
@PostMapping("/customer")public CustomerData saveCustomer(final @RequestBody CustomerData customerData) {
return customerService.saveCustomer(customerData);
}
@DeleteMapping("/customer/{id}")public Boolean deleteCustomer(@PathVariable Long id) {
return customerService.deleteCustomer(id);
}
}
As part of the last step, let’s create the main class for our Spring Boot application:
@SpringBootApplicationpublic class SpringBootHibernateApplication {
private static final Logger log = LoggerFactory.getLogger(SpringBootHibernateApplication.class);
public static void main(String[] args) {
SpringApplication.run(SpringBootHibernateApplication.class, args);
}
We will create few records in the system using the POST method. We are using the Postman for this demo but you can use any other REST client.
Retrieving all customers from the system GET /customers
Retrieving customer information from the system by customer id GET /customers/customer/2
Delete customer information from by customer id DELETE /customers/customer/2
Updated Customer List
How does CodersArts helps you ?
CodersArts provide :
Spring boot assignment Help
Help in development Projects
Mentorship from Experts Live 1:1 session
Course and Project completions
CourseWork help
Comentários