Spring Boot with Hibernate integration

This commit is contained in:
Umesh Awasthi
2020-02-12 21:33:29 -08:00
parent 712de71b1c
commit 7e6c1008c8
9 changed files with 258 additions and 21 deletions

View File

@@ -0,0 +1,16 @@
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
### Guides
The following guides illustrate how to use some features concretely:
* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/)
* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/)
* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/)
* [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/)
* [Accessing data with MySQL](https://spring.io/guides/gs/accessing-data-mysql/)

View File

@@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.javadevjournal</groupId>

View File

@@ -8,8 +8,10 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing
public class SpringBootHibernateApplication {
private static final Logger log = LoggerFactory.getLogger(SpringBootHibernateApplication.class);
@@ -18,7 +20,7 @@ public class SpringBootHibernateApplication {
SpringApplication.run(SpringBootHibernateApplication.class, args);
}
@Bean
/*@Bean
public CommandLineRunner demo(CustomerRepository repository) {
return (args) -> {
@@ -33,5 +35,5 @@ public class SpringBootHibernateApplication {
log.info(customer.toString());
}
};
}
}*/
}

View File

@@ -0,0 +1,58 @@
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;
/**
* <p>Get all customer data in the system.For production system you many want to use
* pagination.</p>
* @return List<CustomerData>
*/
@GetMapping
public List<CustomerData> getCustomers(){
return customerService.getAllCustomers();
}
/**
* Method to get the customer data based on the ID.
* @param id
* @return CustomerData
*/
@GetMapping("/customer/{id}")
public CustomerData getCustomer(@PathVariable Long id){
return customerService.getCustomerById(id);
}
/**
* Post request to create customer information int the system.
* @param customerData
* @return
*/
@PostMapping("/customer")
public CustomerData saveCustomer(final @RequestBody CustomerData customerData){
return customerService.saveCustomer(customerData);
}
/**
* Delete customer from the system based on the ID. The method mapping is similar to the getCustomer with difference of
* @DeleteMapping and @GetMapping
* @param id
* @return
*/
@DeleteMapping("/customer/{id}")
public Boolean deleteCustomer(@PathVariable Long id){
return customerService.deleteCustomer(id);
}
}

View File

@@ -1,11 +1,14 @@
package com.javadevjournal.data;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Customer {
@Id
@@ -15,6 +18,14 @@ public class Customer {
private String lastName;
private String email;
@Column(updatable = false, nullable = false)
@CreatedDate
private LocalDateTime createdTime;
@Column(nullable = false)
@LastModifiedDate
private LocalDateTime updatedTime;
public Customer() {
}
@@ -53,6 +64,22 @@ public class Customer {
this.email = email;
}
public LocalDateTime getCreatedTime() {
return createdTime;
}
public void setCreatedTime(LocalDateTime createdTime) {
this.createdTime = createdTime;
}
public LocalDateTime getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(LocalDateTime updatedTime) {
this.updatedTime = updatedTime;
}
@Override
public String toString() {
return "Customer{" +

View File

@@ -0,0 +1,44 @@
package com.javadevjournal.dto;
public class CustomerData {
private Long id;
private String firstName;
private String lastName;
private String email;
public CustomerData() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@@ -1,19 +1,13 @@
package com.javadevjournal.service;
import com.javadevjournal.data.Customer;
import com.javadevjournal.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javadevjournal.dto.CustomerData;
import java.util.List;
@Service
public class CustomerService {
public interface CustomerService {
@Autowired
private CustomerRepository customerRepository;
public List<Customer> getCustomers(){
return customerRepository.findAll();
}
CustomerData saveCustomer(CustomerData customer);
boolean deleteCustomer(final Long customerId);
List<CustomerData> getAllCustomers();
CustomerData getCustomerById(final Long customerId);
}

View File

@@ -0,0 +1,94 @@
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")
public class DefaultCustomerService implements CustomerService{
@Autowired
private CustomerRepository customerRepository;
/**
* Create a customer based on the data sent to the service class.
* @param customer
* @return DTO representation of the customer
*/
@Override
public CustomerData saveCustomer(CustomerData customer) {
Customer customerModel = populateCustomerEntity(customer);
return populateCustomerData(customerRepository.save(customerModel));
}
/**
* Delete customer based on the customer ID.We can also use other option to delete customer
* based on the entoty (passing JPA entity class as method parameter)
* @param customerId
* @return boolean flag indicating the request status
*/
@Override
public boolean deleteCustomer(Long customerId) {
customerRepository.deleteById(customerId);
return true;
}
/**
* Method to return list of all the available customers in the system.This is a simple
* implementation but you might want to use pagination in the real world example.
* @return list of customer
*/
@Override
public List<CustomerData> getAllCustomers() {
List<CustomerData> customers = new ArrayList<>();
List<Customer> customerList = customerRepository.findAll();
customerList.forEach(customer -> {
customers.add(populateCustomerData(customer));
});
return customers;
}
/**
* Get customer by ID.The service will send the customer data else will throw the exception.
* @param customerId
* @return CustomerData
*/
@Override
public CustomerData getCustomerById(Long customerId) {
return populateCustomerData( customerRepository.findById(customerId).orElseThrow(() -> new EntityNotFoundException("Customer not found")));
}
/**
* Internal method to convert Customer JPA entity to the DTO object
* for frontend data
* @param customer
* @return CustomerData
*/
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;
}
/**
* Method to map the frontend customer object to the JPA customer entity.
* @param customerData
* @return Customer
*/
private Customer populateCustomerEntity(CustomerData customerData){
Customer customer = new Customer();
customer.setFirstName(customerData.getFirstName());
customer.setLastName(customerData.getLastName());
customer.setEmail(customerData.getEmail());
return customer;
}
}

View File

@@ -1,7 +1,9 @@
spring.jpa.generate-ddl=true
#spring.jpa.generate-ddl=true
spring.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
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update