Wednesday 27 June 2018

Enable SSL in Spring Boot


Enabling SSL using HTTPS in Spring Boot


At first step, we need to create a Self Signed Certificate using KeyTool command.

STEP - 1

C:\Users\gaurav>keytool -genkey -alias selfsigned_localhost_sslserver -keyalg RSA -keysize 2048 -
validity 700 -keypass changeit -storepass changeit -keystore name.jks



STEP - 2

To Verify the details available in the generated JKS file:-
C:\Users\gaurav>keytool -list -keystore ssl-server.jks



STEP - 3:- Go to Site http://start.spring.io/

Create a maven project by adding the required dependencies like Web and also select a spring boot version. Few dependency will come as default. Then generate the maven project and import in your IDE

Create a Spring Boot Project by following below steps


STEP - 4

After Import project Structure will look below:-



STEP - 5

Place the generated JKS files in resources folder.

STEP - 6

Create a controller called SSLServerController.java

package com.gaurav.boot.ssl.enable.tomcat;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SSLServerController{
@RequestMapping(method = RequestMethod.GET, value="/rest")
public String greetingService(@RequestParam String name){
System.out.println("Inside REST controller method ()");
return "Welcome "+name;
}
}

STEP - 7

In application.properties file place the below mentioned properties

server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

STEP - 8

Run the application as Spring Boot application by right clicking on Application.java -> Run As-> Spring Boot App.



STEP - 9

Now, Open the Browser and hit the REST URL like below:-

Here REST url will be https://localhost:8443/rest?name=Gaurav






Saturday 16 June 2018

Hibernate One2One Mapping with Spring Boot

One 2 One Hibernate Mapping with Spring Boot

In Hibernate One to One mapping, One Object is associated with exactly one occurrence of another Object.

We can think about the user and it's corresponding user_office_profile.

Each user will have only one office_profile for his unique identification.



  •     Open http://start.spring.io
  •     Click on Switch to Full Version
  •     Enter Artifact as “com.gaurav”
  •     Change Package Name to “springboot.hibernate.mapping”
  •     Select Web, Dev Tools, JPA and Mysql dependencies.
  •     Click Generate Project to generate and download the project.



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.gaurav</groupId>
<artifactId>springboot.hibernate.mapping</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>springboot.hibernate.mapping</name>
<description>Demo project for Spring Boot and Hibernate mappings</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.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>
</properties>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>

application.properties

server.port=9595

# MySQL settings
spring.datasource.url=jdbc:mysql://localhost:3306/experiment
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver.class=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update


# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug   

Model Class

User.java

package com.gaurav.springboot.hibernate.mapping.model;


import java.io.Serializable;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

import javax.validation.constraints.Size;

@Entity
@Table(name = "users")
public class User implements Serializable {


private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(unique = true)
private String email;

@Size(max = 128)
private String password;

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user")
private UserOfficeProfile userOfficeProfile;


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;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public UserOfficeProfile getUserOfficeProfile() {
return userOfficeProfile;
}

public void setUserOfficeProfile(UserOfficeProfile userOfficeProfile) {
this.userOfficeProfile = userOfficeProfile;
}

}

UserOfficeProfile.java

package com.gaurav.springboot.hibernate.mapping.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "user_office_profile")
public class UserOfficeProfile implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "phone_number")
private String phoneNumber;

private String gender;

@Temporal(TemporalType.DATE)
@Column(name = "dob")
private Date dateOfBirth;

private String address;

private String street;

private String city;

private String state;

private String country;

@Column(name = "zip_code")
private String zipCode;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;



public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public Date getDateOfBirth() {
return dateOfBirth;
}

public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public String getZipCode() {
return zipCode;
}

public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

}


UserRepository.java

package com.gaurav.springboot.hibernate.mapping.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.gaurav.springboot.hibernate.mapping.model.User;

@Repository
public interface UserRepository extends CrudRepository<User, Long> {

}

UserOfficeProfileRepository.java

package com.gaurav.springboot.hibernate.mapping.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.gaurav.springboot.hibernate.mapping.model.UserOfficeProfile;

@Repository
public interface UserOfficeProfileRepository extends CrudRepository<UserOfficeProfile, Long> {

}

HibernateOneToOneDemoApplication.java

package com.gaurav.springboot.hibernate.mapping;

import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.gaurav.springboot.hibernate.mapping.model.User;
import com.gaurav.springboot.hibernate.mapping.model.UserOfficeProfile;
import com.gaurav.springboot.hibernate.mapping.repository.UserOfficeProfileRepository;
import com.gaurav.springboot.hibernate.mapping.repository.UserRepository;

@SpringBootApplication
public class HibernateOneToOneDemoApplication implements CommandLineRunner {

@Autowired
private UserRepository userRepository;

@Autowired
private UserOfficeProfileRepository userOfficeProfileRepository;

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

@Override
public void run(String... args) throws Exception {

// Removing all the child records from existing database.
userOfficeProfileRepository.deleteAll();

// Removing all the parent records from existing database.
userRepository.deleteAll();

// Creating Parent Object instance
User user = new User();
user.setFirstName("Gaurav");
user.setLastName("kumar");
user.setEmail("gaurav@gmail.com");
user.setPassword("TEST_PASSWORD");

Calendar dateOfBirth = Calendar.getInstance();
dateOfBirth.set(1985, 11, 28);

// Creating a Child Object instance

UserOfficeProfile userOfficeProfile = new UserOfficeProfile();
userOfficeProfile.setPhoneNumber("+91-8901236547");
userOfficeProfile.setGender("Male");
userOfficeProfile.setDateOfBirth(dateOfBirth.getTime());
userOfficeProfile.setAddress("31 SC");
userOfficeProfile.setStreet("X Road");
userOfficeProfile.setCity("HYDERABAD");
userOfficeProfile.setState("Telangana");
userOfficeProfile.setCountry("India");
userOfficeProfile.setZipCode("500123");

// placing child reference with respect to parent entity(user)
user.setUserOfficeProfile(userOfficeProfile);

// placing parent reference with respect to child
// entity(userOfficeProfile)
userOfficeProfile.setUser(user);

// Saving Parent Reference (which will save the child also)
userRepository.save(user);

}
}

Table schema

CREATE TABLE users (id BIGINT NOT NULL AUTO_INCREMENT, 
email VARCHAR(100) NOT NULL, 
first_name VARCHAR(65) NOT NULL, 
last_name VARCHAR(65), 
PASSWORD VARCHAR(128) NOT NULL, 
PRIMARY KEY (id))

CREATE TABLE user_office_profile (id BIGINT NOT NULL AUTO_INCREMENT, address VARCHAR(255), city VARCHAR(255), country VARCHAR(255), dob DATE, gender VARCHAR(255), 
phone_number VARCHAR(255), 
state VARCHAR(255), 
street VARCHAR(255), 
zip_code VARCHAR(255), 
user_id BIGINT NOT NULL, PRIMARY KEY (id)) 

OUTPUT

2018-06-16 18:17:24 INFO  o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 9595 (http) with context path ''
2018-06-16 18:17:24 INFO  c.g.s.h.m.HibernateOneToOneDemoApplication - Started HibernateOneToOneDemoApplication in 5.177 seconds (JVM running for 6.037)
2018-06-16 18:17:24 INFO  o.h.h.i.QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - delete from user_office_profile
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - delete from users
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - insert into users (email, first_name, last_name, password) values (?, ?, ?, ?)
2018-06-16 18:17:25 DEBUG org.hibernate.SQL - insert into user_office_profile (address, city, country, dob, gender, phone_number, state, street, user_id, zip_code) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)


Wednesday 13 June 2018

Spring Boot RESTful API Documentation Using Swagger 2

Spring Boot With Swagger 2


What is Swagger?

Swagger allows you to describe the structure of your APIs so that machines can read them. The ability of APIs to describe their own structure is the root of all awesomeness in Swagger. 

Swagger is a specification for documenting REST API. It specifies the format (URL, method, and representation) to describe REST web services. It provides also tools to generate/compute the documentation from application code. 

Swagger scans your code and exposes the documentation on some URL. 

The Swagger documentation uses and implements HATEOAS: once a client reaches the documentation  homepage, it can follow the link to learn more about the API of the various resources the system exposes.



Project Structure





pom.xml

<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.gaurav</groupId>
<artifactId>spring.boot.swagger</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

application.properties

server.port=9595

EmployeeController.java

package com.gaurav.spring.boot.swagger.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {

private static Map<Long, String> employeeMap = new HashMap<Long, String>();

@RequestMapping(method = RequestMethod.GET, value = "/rest/gaurav/list/employee")
public String listEmployees() {
employeeMap.put(new Long(1001), "Gaurav");
employeeMap.put(new Long(1234), "Aaditya");
employeeMap.put(new Long(11), "Shivam");
employeeMap.put(new Long(101), "Kumar");

return employeeMap.toString();
}

@RequestMapping(method = RequestMethod.POST, value = "/rest/gaurav/save/employee")
public String saveEmployeeName(@RequestParam Long id, @RequestParam String name) {
employeeMap.put(new Long(id), name);
return employeeMap.toString();
}

@RequestMapping(method = RequestMethod.PUT, value = "/rest/gaurav/update/employee")
public String updateEmployeeName(@RequestParam Long id, @RequestParam String name) {
String result = null;
if(employeeMap.get(id)!= null){
employeeMap.put(new Long(id), name);
return employeeMap.toString();
}else{
result = "Employee not found with the given ID:"+id;
return result;
}
}

@RequestMapping(method = RequestMethod.DELETE, value = "/rest/gaurav/delete/employee")
public String removeEmployeeName(@RequestParam Long id) {
String result = null;
if(employeeMap.get(id)!= null){
employeeMap.remove(new Long(id));
return employeeMap.toString();
}
else{
result = "Employee not found with the given ID:"+id;
return result;
}

}

}


SwaggerConfiguration.java

package com.gaurav.spring.boot.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.common.base.Predicate;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
import static com.google.common.base.Predicates.or;

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

@Bean
public Docket postsApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("public-api")
.apiInfo(apiInfo()).select().paths(postPaths()).build();
}

private Predicate<String> postPaths() {
return or(regex("/rest/api.*"), regex("/rest/gaurav.*"));
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Spring Boot + Swagger API")
.description("Spring Boot & Swagger API reference for developers")
.termsOfServiceUrl("http://javatipsbygaurav.blogspot.com/")
.contact("cutegiftsmile@gmail.com").license("javatipsbygaurav License")
.licenseUrl("cutegiftsmile@gmail.com").version("1.0").build();
}

}

Application.java

package com.gaurav.spring.boot.swagger;

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

@SpringBootApplication
public class Application {

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

After triggering the Application.java using

Right Click -> Run As -> Spring Boot App


We can hit the below URL. I configured tomcat at port 9595.
http://localhost:9595/swagger-ui.html


List of All Operations:



List Employees operation


Save Employee Operation



Update Employee Operation


Delete Employee Operation


Monday 4 June 2018

Hibernate and JPA Integration with Spring Boot

Spring Boot With Hibernate & MYSQL


Open http://start.spring.io/ to create a Spring Boot Project.

Selected dependencies for this project are : Web, JPA, MySQL, DevTools


After Generating the above project, use import project into Eclipse option.
File -> Import -> Existing Maven Project.



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.gaurav</groupId>
<artifactId>spring.boot.hibernate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>spring.boot.hibernate</name>
<description>Demo project for Spring Boot With Hibernate And MySQL</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.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>
</properties>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


</project>



JPA Entity or Model Class

package com.gaurav.spring.boot.hibernate.model;

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

@Entity
@Table(name = "Employee")
public class Employee {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private String name;

@Column(name="designation")
private String designation;

public Employee() {
super();
}

public Employee(Long id, String name, String designation) {
super();
this.id = id;
this.name = name;
this.designation = designation;
}

public Employee(String name, String designation) {
super();
this.name = name;
this.designation = designation;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", designation=" + designation + "]";
}

/**
* @return the designation
*/
public String getDesignation() {
return designation;
}

/**
* @param designation the designation to set
*/
public void setDesignation(String designation) {
this.designation = designation;
}
}

Repository class to read Employee entity information by extending CrudRepository

package com.gaurav.spring.boot.hibernate.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.gaurav.spring.boot.hibernate.model.Employee;



@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Long> {

Employee findById(long empId);
Iterable<Employee> findAll();
}

/src/main/resources/application.properties

server.port=9595

# MySQL settings
spring.datasource.url=jdbc:mysql://IP:3306/experiment
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver.class=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false

# logging
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
logging.level.org.hibernate.SQL=debug

employee.sql

/*
SQLyog Community v11.52 (32 bit)
MySQL - 5.6.23-log 
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

create table `employee` (
`id` bigint (10),
`name` varchar (150),
`designation` varchar (150)
); 
insert into `employee` (`id`, `name`, `designation`) values('10001','Aaditya','Senior Developer');
insert into `employee` (`id`, `name`, `designation`) values('11002','Gaurav','Technical Lead');
insert into `employee` (`id`, `name`, `designation`) values('51345','Kumar','System Analyst');


Spring Boot Initializer Class :- Application.java

package com.gaurav.spring.boot.hibernate;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import com.gaurav.spring.boot.hibernate.model.Employee;
import com.gaurav.spring.boot.hibernate.repository.EmployeeRepository;

@SpringBootApplication
@ComponentScan("com.gaurav.spring.boot.hibernate.*")
public class Application implements CommandLineRunner {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
EmployeeRepository repository;

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

public static final String NEW_EMPLOYEE_NAME = "Sunita";

Long empId;

@Override
public void run(String... arg0) throws Exception {

logger.info("Finding a record based on passed empId", repository.findById(11002));

logger.info("First call for finding all users -> {}", repository.findAll());

Employee employee = new Employee();
employee.setName(NEW_EMPLOYEE_NAME);
employee.setDesignation("Senior Manager");

// Inserting a record into the database
logger.info("Inserting new employee, where employee name is: " + employee.getName(), repository.save(employee));

logger.info("Record with the employee " + employee.getName() + " inserted Successfully");

Iterator<Employee> employeeIterator = repository.findAll().iterator();
while (employeeIterator.hasNext()) {
Employee emp = employeeIterator.next();
if (emp.getName().equals(NEW_EMPLOYEE_NAME)) {
empId = emp.getId();
}
}

logger.info("Second call after insert a new Employee record for finding all users -> {}", repository.findAll());

// Updating a record into the database

logger.info("Update the employee record", repository.save(new Employee(empId, "Krishna", "Senior Manager")));

logger.info("Third call after insert a new Employee record for finding all users -> {}", repository.findAll());

// Deleting a record from the database
logger.info("Deleting a employee record, where employee id is:" + empId);
repository.deleteById(empId);

logger.info("Fourth call for finding all users after deleting an employee record whose employee id is " + empId
+ " -> {}", repository.findAll());

}
}

OUTPUT

2018-06-04 15:50:19 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_0_, employee0_.designation as designat2_0_0_, employee0_.name as name3_0_0_ from employee employee0_ where employee0_.id=?

2018-06-04 15:50:19 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Finding a record based on passed empId
2018-06-04 15:50:19 INFO  o.h.h.i.QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory
2018-06-04 15:50:19 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:19 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - First call for finding all users -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst]]
2018-06-04 15:50:19 DEBUG org.hibernate.SQL - insert into employee (designation, name) values (?, ?)

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Inserting new employee, where employee name is: Sunita
2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Record with the employee Sunita inserted Successfully
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Second call after insert a new Employee record for finding all users -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst], Employee [id=51355, name=Sunita, designation=Senior Manager]]

2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_0_, employee0_.designation as designat2_0_0_, employee0_.name as name3_0_0_ from employee employee0_ where employee0_.id=?

2018-06-04 15:50:20 DEBUG org.hibernate.SQL - update employee set designation=?, name=? where id=?
2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Update the employee record
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Third call after insert a new Employee record for finding all users -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst], Employee [id=51355, name=Krishna, designation=Senior Manager]]

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Deleting a employee record, where employee id is:51355
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_0_, employee0_.designation as designat2_0_0_, employee0_.name as name3_0_0_ from employee employee0_ where employee0_.id=?
2018-06-04 15:50:20 DEBUG org.hibernate.SQL - delete from employee where id=?

2018-06-04 15:50:20 DEBUG org.hibernate.SQL - select employee0_.id as id1_0_, employee0_.designation as designat2_0_, employee0_.name as name3_0_ from employee employee0_

2018-06-04 15:50:20 INFO  c.g.s.b.h.Application$$EnhancerBySpringCGLIB$$d3af184a - Fourth call for finding all users after deleting an employee record whose employee id is 51355 -> [Employee [id=10001, name=Aaditya, designation=Senior Developer], Employee [id=11002, name=Gaurav, designation=Technical Lead], Employee [id=51345, name=Kumar, designation=System Analyst]]


Sunday 3 June 2018

TreeSet Example Using Comparator

TreeSet Example


In the below example, we can see that how to use Comparator to use custom sorting. Suppose we have a third party class which is not implementing Comparable interface and we needs to add that custom class in TreeSet. At that situation, we can use the below technique to implement the custom sorting using Comparator interface and TreeSet constructor which accepts Comparator object.

package com.gaurav.mapexample;

import java.util.Comparator;
import java.util.TreeSet;

class Employee {
private String name;
private double salary;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public double getSalary() {
return salary;
}

public void setSalary(double salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + "]";
}

public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}

}
class EmployeeNameComparator implements Comparator<Employee>{
public int compare(Employee emp1, Employee emp2){
return emp1.getName().compareTo(emp2.getName());
}
}

class EmployeeSalaryComparator implements Comparator<Employee>{
public int compare(Employee emp1, Employee emp2){
if(emp1.getSalary() > emp2.getSalary())
return 1;
else if(emp1.getSalary() < emp2.getSalary())
return -1;
else
return 0;
}
}

public class TreeSetExampleWithComparator {
public static void main(String args[]){
TreeSet<Employee> employeeNameComp = new TreeSet<Employee>(new EmployeeNameComparator());
employeeNameComp.add(new Employee("Gaurav", 115678.92));
employeeNameComp.add(new Employee("Shivam", 165678.92));
employeeNameComp.add(new Employee("Suresh", 195678.92));
employeeNameComp.add(new Employee("Sunita", 85678.92));
employeeNameComp.add(new Employee("Aaditya", 55678.92));

//Uses of Stream & for each methods of collection which is introduced in java 8.
employeeNameComp.stream().forEach(i->System.out.println(i));

System.out.println("###################################");
TreeSet<Employee> employeeSalaryComp = new TreeSet<Employee>(new EmployeeSalaryComparator());
employeeSalaryComp.add(new Employee("Gaurav", 115678.92));
employeeSalaryComp.add(new Employee("Shivam", 165678.92));
employeeSalaryComp.add(new Employee("Suresh", 195678.92));
employeeSalaryComp.add(new Employee("Sunita", 85678.92));
employeeSalaryComp.add(new Employee("Aaditya", 55678.92));

//Uses of Stream & for each methods of collection which is introduced in java 8.
employeeSalaryComp.stream().forEach(i->System.out.println(i));

}
}

Output:

Employee [name=Aaditya, salary=55678.92]
Employee [name=Gaurav, salary=115678.92]
Employee [name=Shivam, salary=165678.92]
Employee [name=Sunita, salary=85678.92]
Employee [name=Suresh, salary=195678.92]
###################################
Employee [name=Aaditya, salary=55678.92]
Employee [name=Sunita, salary=85678.92]
Employee [name=Gaurav, salary=115678.92]
Employee [name=Shivam, salary=165678.92]
Employee [name=Suresh, salary=195678.92]