Jenkins interview questions and answer

What is Jenkins software?

Jenkins is a self-contained, open source automation server which can be used to automate all sorts of tasks related to building, testing, and delivering or deploying software.

Jenkins is one of the leading open source automation servers available. Jenkins has an extensible, plugin-based architecture, enabling developers to create 1,400+ plugins to adapt it to a multitude of build, test and deployment technology integrations

What is the minimum JRE required to run jenkins 2.1?

JDK 8 or JRE 8

What is a Jenkins Pipeline?

Jenkins Pipeline (or simply “Pipeline”) is a suite of plugins which supports implementing and integrating continuous delivery pipelines into Jenkins.

What is continuous delivery pipeline?

A continuous delivery pipeline is an automated expression of your process for getting software from version control right through to your users and customers.

What is an agent in jenkins ?

The agent directive tells Jenkins where and how to execute the Pipeline, or subset thereof. As you might expect, the agent is required for all Pipelines.

What is post section in jenkins?

The post section of a Pipeline is guaranteed to run at the end of a Pipeline’s execution, we can add some notification or other steps to perform finalization, notification, or other end-of-Pipeline tasks.

What is Jenkins used for Devops?

Jenkins automate the CI / CD process in Devops layer.

Which is the best continuous integration tool?

1. Jenkins, Teamcity etc…

What is CI and CD process?

Continuous integration
Developers practicing continuous integration merge their changes back to the main branch as often as possible

Continuous delivery
Continuous delivery is an extension of continuous integration to make sure that you can release new changes to your customers quickly in a sustainable way.

What is a Jenkinsfile?

Jenkinsfile is a text file that contains the definition of a Jenkins Pipeline and is checked into source control.

What is an SCM in Jenkins?

Source code managment in jenkis is the first step in jenkins to download latest source code from git or svn etc, to start the build process.

 

 

Spring boot jetty example

Common servlet container settings can be configured using Spring Environment properties. Usually you would define the properties in your application.properties file.

Spring boot jetty as embedded server

Step 1: exclude tomcat from spring boot web starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

  Step 2: Now add Jetty dependency – spring-boot-starter-jetty maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Thats All…

How to run

mvn spring-boot:run

 

Download

Jetty as embedded server maven

 

Alternatively you can try Programmatic customization for jetty configuration

If you need to configure your embedded servlet container programmatically you can register a Spring bean that implements the EmbeddedServletContainerCustomizer interface. EmbeddedServletContainerCustomizer provides access to the ConfigurableEmbeddedServletContainer which includes numerous customization setter methods.

import org.springframework.boot.context.embedded.*;
        import org.springframework.stereotype.Component;

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(9000);
    }

}

 

Spring boot import configuration

 

You don’t need to put all your @Configuration into a single class. The @Import annotation  can be used to import additional configuration classes.

Spring boot @Import example

package com.candidjava.spring.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan(basePackages = "com.candidjava")
@Import({ SpringConfiguration.class })
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

 

SpringConfiguration class

package com.candidjava.spring.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@Configuration
public class SpringConfiguration extends WebMvcConfigurerAdapter{

    @Bean(name = "jspViewResolver")
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        return viewResolver;
    }

}

 

SpringWebIntializer class

package com.candidjava.spring.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;


public class SpringWebIntializer implements WebApplicationInitializer {

    public void onStartup(ServletContext container) throws ServletException {
        // TODO Auto-generated method stub
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setServletContext(container);
        ServletRegistration.Dynamic servlet = container.addServlet(
                "dispatcher", new DispatcherServlet(context));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

 

Spring controller

package com.candidjava.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.candidjava.spring.entity.User;

@Controller
public class UserController {

    @GetMapping("/")
    public ModelAndView register(User user) {
        return new ModelAndView("register");
    }

    @PostMapping("/register")
    public ModelAndView create(@ModelAttribute("user") User user) {
        ModelAndView model = new ModelAndView("view");
        // user bean will be automatically binded to view refer @ModelAttribute
        System.out.println(user.getName());
        model.addObject("name",user.getName());
        model.addObject("gender",user.getGender());
        model.addObject("email", user.getEmail());
        model.addObject("country", user.getCountry());
        model.addObject("password", user.getPassword());
        return model;
    }

    @GetMapping("/register")
    public ModelAndView viewData(User user) {

        ModelAndView model = new ModelAndView("register");
        return model;
    }

}

 

User

package com.candidjava.spring.entity;

import java.util.List;

public class User
{
    private String name;

    private List<String> language;

    private String country;

    private String gender;

    private String password;

    private String email;

    public String getName() {
        return name;
    }

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

    public List<String> getLanguage() {
        return language;
    }

    public void setLanguage(List<String> language) {
        this.language = language;
    }

    public String getCountry() {
        return country;
    }

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

    public String getGender() {
        return gender;
    }

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

    public String getPassword() {
        return password;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

 

index.jsp

<meta http-equiv="refresh" content="0; URL='index'" />

 

register.jsp

    <%@page import="org.springframework.validation.ObjectError"%>
<%@ page import="com.candidjava.spring.entity.User" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
.err
{
color:red;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>

   <h2>Simple spring form handling</h2>
   <form action="register" method="POST" modelAttribute="user">
   Name:<input type="text"name="name"/><br>
Gender : Male<input type="radio" name="gender" value="male" path="gender"/>   Female<input type="radio"  name="gender" value="female" path="gender"/><br>
   Email : <input type="text" name="email" path="email"/><br>
   Country : <select name="country" path="country">
               <option value="">select country</option>
               <option value="india">INDIA</option>
               <option value="usa">USA</option>
               <option value="china">CHINA</option>
             </select>
             
            <br>  
            Password:<input type="password" name="password" path="password"/><br>  
            <input type="submit" value="submit" />
   </form>
</body>
</html>

 

view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="com.candidjava.spring.entity.User" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>User Info</h2>

<strong>User Name </strong>: ${name} <br>
<strong>Gender </strong> : ${gender}<br>
<strong>Email </strong> : ${email}<br>
<strong>Country </strong>: ${country} <br> 
<strong>Password</strong>: ${password}<br> 
   
</body>
</html>

 

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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>spring-boot-webapp-import</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-webapp-import</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>

        <!-- This is a web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- JSTL for JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Need this to compile JSP,
            tomcat-embed-jasper version is not working, no idea why -->
        <dependency>
            <groupId>org.eclipse.jdt.core.compiler</groupId>
            <artifactId>ecj</artifactId>
            <version>4.6.1</version>
            <scope>provided</scope>
        </dependency>

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

How to run

mvn spring-boot:run

 

Screenshot

 

Download

Spring boot @import maven

 

 

Spring boot interview questions and answers part 3

Part 1  | Part 2 | Part 3

What is Hot swapping in spring boot?

Reloading the changes without restarting the server is called hot swapping, Modern IDEs (Eclipse, IDEA, etc.) all support hot swapping of bytecode,  so if you make a change that doesn’t affect class or method signatures it should reload cleanly with no side effects.

How do you Switch off the Spring Boot security configuration?

If you define a @Configuration with @EnableWebSecurity anywhere in your application it will switch off the default webapp security settings in Spring Boot.

How to execute Spring Batch jobs on startup?

Spring Batch auto-configuration is enabled by adding @EnableBatchProcessing (from Spring Batch) somewhere in your context. By default it executes all Jobs in the application context on startup

Does spring boot need Logging and what is the default one?

Spring Boot has no mandatory logging dependency, except for the Commons Logging API.

How do you configure Configure Logback for logging?

If you put a logback.xml in the root of your classpath it will be picked up from there

How do you Configure Log4j for logging?

Spring Boot supports Log4j 2 for logging configuration if it is on the classpath. If you are using the starters for assembling dependencies that means you have to exclude Logback and then include log4j 2 instead

How do you write a Write a JSON REST service in spring boot?

Any Spring @RestController in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath

How do you Write an XML REST service in spring boot?

If you have the Jackson XML extension (jackson-dataformat-xml) on the classpath, it will be used to render XML responses

What is the default Multipart File Uploads size in spring boot?

By default Spring Boot configures Spring MVC with a maximum file of 1MB per file and a maximum of 10MB of file data in a single request.

How do you Enable HTTP response compression in spring boot?

HTTP response compression is supported by Jetty, Tomcat, and Undertow. It can be enabled by adding server.compression.enabled=true in application.properties

How do you add Add a Servlet, Filter or Listener to an application ?

There are two ways to add Servlet, Filter, ServletContextListener and the other listeners supported by the Servlet spec to your application. You can either provide Spring beans for them, or enable scanning for Servlet components.

How do you Change tomcat or jetty HTTP port?

You can change the tomcat http port by changing default http property in application.properties file.

Part 1  | Part 2 | Part 3

Spring boot interview questions and answers part 2

Part 1  | Part 2 | Part 3

What is spring-boot-devtools ?

Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes.

What is LiveReload?

The spring-boot-devtools module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed. LiveReload browser extensions are freely available for Chrome, Firefox and Safari from livereload.com.

How to exclude auto restart for static files?

By default changing resources in /META-INF/maven, /META-INF/resources, /resources, /static, /public or /templates will not trigger a restart
But If you want to customize these exclusions you can use the spring.devtools.restart.exclude property
if you want to keep those defaults and add additional exclusions, use the spring.devtools.restart.additional-exclude property instead

How to start spring boot application in debug mode?

java -jar myproject-0.0.1-SNAPSHOT.jar –debug

Advantage of YAML file than Properties file?

YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. The SpringApplication class will automatically support YAML as an alternative to properties whenever you have the SnakeYAML library on your classpath

Different ways to load YAML file in Spring boot?

1. YamlPropertiesFactoryBean will load YAML as Properties
2. YamlMapFactoryBean will load YAML as a Map

Advantage of spring Externalized Configuration?

Externalize your configuration to work with the same application code in different environments. You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration.

What are Profiles in spring boot?

Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. Any @Component or @Configuration can be marked with @Profile to limit when it is loaded

How to write custom log configuration in spring boot?

You can force Spring Boot to use a particular logging system using the org.springframework.boot.logging.LoggingSystem system property. The value should be the fully-qualified class name of a LoggingSystem implementation. You can also disable Spring Boot’s logging configuration entirely by using a value of none.

How do you customize Favicon in spring boot web application?

Spring Boot looks for a favicon.ico in the configured static content locations and the root of the classpath (in that order). If such file is present, it is automatically used as the favicon of the application.

How spring boot handles error in application?

Spring Boot provides an /error mapping by default that handles all errors in a sensible way, and it is registered as a ‘global’ error page in the servlet container.

How do you Create a deployable war file in spring boot?

Step1: Extend SpringBootServletInitializer and override its configure method

Step 2: Change packing type to war in pom.xml or in build.gradle

Step 3: Mark the embedded servlet container dependency as provided

Part 1  | Part 2 | Part 3

Spring boot interview questions and answers

Part 1  | Part 2 | Part 3

What is Spring Boot?

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.

You can use Spring Boot to create Java applications that can be started using java -jar or more traditional war deployments.

 

Advantages of spring boot application?

Provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).

Opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss

Absolutely no code generation and no requirement for XML configuration.

Provide a radically faster and widely accessible getting started experience for all Spring development.

 

Spring boot System requirements?

Spring Boot 1.5.9.RELEASE requires

Java 7 +

Spring 4.3.13 +

For build support

Maven 3.2+

Gradle 2.9+

Container Support

Tomcat 7+

Jetty 8+ (Jetty 9.3 requires JDK 8 +)

 

Use of @EnableAutoConfiguration annotation?

This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added.

 

What is Spring Boot Starter?

Spring Boot provides a number of “Starters” that make easy to manage dependencies for your project.

 

What is spring-boot-starter-parent?

The spring-boot-starter-parent is a special starter that makes Maven or Gradle dependency-management easier by adding jars to your classpath.

 

What is spring-boot-starter-web?

This starter will add Tomcat and Spring MVC dependency to our application and its default configuration

 

How to create an executable jar using spring boot?

Add this below plugin to pom.xml

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

Use mvn clean package to create executable jar file

 

How do you run and stop spring boot executable jar?

Open cmd or shell window and use java -jar as shown below

$ java -jar myproject-0.0.1-SNAPSHOT.jar

To stop use ctrl+C

 

How do you change JDK version in spring boot?

Java 1.6 as the default compiler level.
You can overwrite it by adding java.version property tag as shown below

<properties>
    <java.version>1.8</java.version>
</properties>

 

How to disable specific auto-configuration in spring boot?

You can use exclude property as shown below to disable specific auto configuration

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

 

What is the use of @SpringBootApplication annotation?

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes

Since many spring Boot developers have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan, spring boot provides you a new annotation @SpringBootApplication as replacement.

 

Part 1  | Part 2 | Part 3

Spring boot jpa mysql example

This tutorial shows you how to integrate Spring boot with spring data jpa mysql database.

Environment Used

Eclipse

Maven

JDK 1.8

Spring Boot 1.4.2

Spring 4.3

Mysql 5.1 or greater

Spring Boot crudrepository example

CrudRepository

package com.candidjava.spring.repository;

import org.springframework.data.repository.CrudRepository;

import com.candidjava.spring.bean.User;
public interface UserRepository extends CrudRepository<User, Long>{

}

application.properties JPA Configuration

logging.level.org.springframework.web=DEBUG
# Database
spring.datasource.driver = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test3
spring.datasource.username = root
spring.datasource.password = root


spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Service Interface

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
    public void createUser(User user);
    public List<User> getUser();
    public User findById(long id);
    public User update(User user, long l);
    public void deleteUserById(long id);
    public User updatePartially(User user, long id);
}

Service Implementation

package com.candidjava.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.repository.UserRepository;

@Service
@Transactional
public class UserServiceImp implements UserService {
    @Autowired
    UserRepository userRepository;

    public void createUser(User user) {
        // TODO Auto-generated method stub
        userRepository.save(user);
    }

    public List<User> getUser() {
        // TODO Auto-generated method stub
        return (List<User>) userRepository.findAll();
    }

    public User findById(long id) {
        // TODO Auto-generated method stub
        return userRepository.findOne(id);
    }

    public User update(User user, long l) {
        // TODO Auto-generated method stub
        return userRepository.save(user);
    }

    public void deleteUserById(long id) {
        // TODO Auto-generated method stub
        userRepository.delete(id);
    }

    public User updatePartially(User user, long id) {
        // TODO Auto-generated method stub
        User usr = findById(id);
        usr.setCountry(user.getCountry());
        return userRepository.save(usr);
    }
}

Controller

package com.candidjava.spring.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/user"})
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {
        List<User> tasks=userService.getUser();
        return tasks;

    }

    @PutMapping(value="/update", headers="Accept=application/json")
    public ResponseEntity<String> updateUser(@RequestBody User currentUser)
    {
        System.out.println("sd");
        User user = userService.findById(currentUser.getId());
        if (user==null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        userService.update(currentUser, currentUser.getId());
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @DeleteMapping(value="/{id}", headers ="Accept=application/json")
    public ResponseEntity<User> deleteUser(@PathVariable("id") long id){
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

    @PatchMapping(value="/{id}", headers="Accept=application/json")
    public ResponseEntity<User> updateUserPartially(@PathVariable("id") long id, @RequestBody User currentUser){
        User user = userService.findById(id);
        if(user ==null){
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        User usr = userService.updatePartially(currentUser, id);
        return new ResponseEntity<User>(usr, HttpStatus.OK);
    }
}

Bean Class

package com.candidjava.spring.bean;

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

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;


@Entity
@Table(name="UserInfo")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

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

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

    private String name;


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

    public String getCountry() {
        return country;
    }

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

}

Application.java

package com.candidjava;

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

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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-Jpa-mysql</artifactId>
    <packaging>jar</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-Jpa-mysql Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- Tomcat embedded container -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <finalName>Spring-Boot-Jpa-mysql</finalName>
    </build>
</project>

How to run

mvn spring-boot:run

Download

Spring boot data JPA mysql maven

 

References

Spring Boot JPA repository – Official site

Spring Boot JPA CurdRepository – Official site

 

Spring boot hibernate crud example

Environment Used

Eclipse

Maven

JDK 1.8

Spring Boot 1.4.2

Spring 4.3

Hibernate 5

Mysql 5.1 or greater

 

Spring boot hibernate mysql example

This tutorial shows you how to integrate spring boot rest service with hibernate framework.

Hibernate Configuration

package com.candidjava.spring.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {

    @Value("${db.driver}")
    private String DB_DRIVER;

    @Value("${db.password}")
    private String DB_PASSWORD;

    @Value("${db.url}")
    private String DB_URL;

    @Value("${db.username}")
    private String DB_USERNAME;

    @Value("${hibernate.dialect}")
    private String HIBERNATE_DIALECT;

    @Value("${hibernate.show_sql}")
    private String HIBERNATE_SHOW_SQL;

    @Value("${hibernate.hbm2ddl.auto}")
    private String HIBERNATE_HBM2DDL_AUTO;

    @Value("${entitymanager.packagesToScan}")
    private String ENTITYMANAGER_PACKAGES_TO_SCAN;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
        hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
        sessionFactory.setHibernateProperties(hibernateProperties);
        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DB_DRIVER);
        dataSource.setUrl(DB_URL);
        dataSource.setUsername(DB_USERNAME);
        dataSource.setPassword(DB_PASSWORD);
        return dataSource;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory().getObject());
        return txManager;
    }
}

Spring boot applications.properties

logging.level.org.springframework.web=DEBUG
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/test
db.username: root
db.password: root

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: update
entitymanager.packagesToScan: com

@RestController

package com.candidjava.spring.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/user"})
public class UserController {
    @Autowired
    UserService userService;

    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") int id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {
        List<User> tasks=userService.getUser();
        return tasks;

    }

    @PutMapping(value="/update", headers="Accept=application/json")
    public ResponseEntity<String> updateUser(@RequestBody User currentUser)
    {
        System.out.println("sd");
        User user = userService.findById(currentUser.getId());
        if (user==null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        userService.update(currentUser, currentUser.getId());
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @DeleteMapping(value="/{id}", headers ="Accept=application/json")
    public ResponseEntity<User> deleteUser(@PathVariable("id") int id){
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

    @PatchMapping(value="/{id}", headers="Accept=application/json")
    public ResponseEntity<User> updateUserPartially(@PathVariable("id") int id, @RequestBody User currentUser){
        User user = userService.findById(id);
        if(user ==null){
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        User usr = userService.updatePartially(currentUser, id);
        return new ResponseEntity<User>(usr, HttpStatus.OK);
    }
}

Bean class

package com.candidjava.spring.bean;

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

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;


@Entity
@Table(name="UserInfo")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

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

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

    private String name;


    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 getCountry() {
        return country;
    }

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

}

Service Interface

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
    public void createUser(User user);
    public List<User> getUser();
    public User findById(int id);
    public User update(User user, int id);
    public void deleteUserById(int id);
    public User updatePartially(User user, int id);
}

Service Impl

package com.candidjava.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.dao.UserDao;

@Service
@Transactional
public class UserServiceImp implements UserService {
    @Autowired
    UserDao userDao;


    public List<User> getUser() {
        // TODO Auto-generated method stub
        return userDao.getUser();
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        return userDao.findById(id);
    }

    public void createUser(User user) {
        // TODO Auto-generated method stub
        userDao.addUser(user);
    }

    public void deleteUserById(int id) {
        // TODO Auto-generated method stub
        userDao.delete(id);
    }
    @Override
    public User updatePartially(User user, int id) {
        userDao.updateCountry(user,id);
        return userDao.findById(id);
    }

    @Override
    public User update(User user,int id) {
        // TODO Auto-generated method stub
        return userDao.update(user, id);
    }

}

Dao Interface

package com.candidjava.spring.dao;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserDao {
    public void addUser(User user);
    public List<User> getUser();
    public User findById(int id);
    public User update(User user, int id);
    public User updateCountry(User user, int id);
    public void delete(int id);
}

Dao Impl

package com.candidjava.spring.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.candidjava.spring.bean.User;
@Repository
public class UserDaoImp implements UserDao{
    @Autowired
    private SessionFactory sessionFactory;

    public void addUser(User user) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
    }

    public List<User> getUser() {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        @SuppressWarnings("unchecked")
        List<User> list= session.createCriteria(User.class).list();
        return list;
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        User user=(User) session.get(User.class,id);
        return user;
    }

    public User update(User val, int id) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        User user =(User)session.get(User.class, id);
        user.setCountry(val.getCountry());
        user.setName(val.getName());
        session.update(user);
        return user;
    }

    public void delete(int id) {
        // TODO Auto-generated method stub
        Session session = sessionFactory.getCurrentSession();
        User user = findById(id);
        session.delete(user);
    }
    @Override
    public User updateCountry(User val, int id){
        Session session = sessionFactory.getCurrentSession();
        User user = (User)session.load(User.class, id);
        user.setCountry(val.getCountry());
        return user;
    }

}

Maven 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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-Restfull</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-Restfull Maven Webapp</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

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

How to run

mvn spring-boot:run

Download

Spring boot hibernate rest maven

 

References

Spring boot hibernate Official website

Spring boot rest service example

Environment used

Eclipse

Maven

JDK 1.8

Spring Boot 1.4.2

Spring 4.3

This post shows you how to use @GetMapping, @PostMapping, @PathMapping, @PutMapping, @DeleteMapping

Spring boot restful web services JSON example

@Controller

package com.candidjava.spring.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value={"/user"})
public class UserController {
    @Autowired
    UserService userService;


    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> getUserById(@PathVariable("id") int id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @PostMapping(value="/create",headers="Accept=application/json")
    public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
        System.out.println("Creating User "+user.getName());
        userService.createUser(user);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

    @GetMapping(value="/get", headers="Accept=application/json")
    public List<User> getAllUser() {
        List<User> tasks=userService.getUser();
        return tasks;

    }

    @PutMapping(value="/update", headers="Accept=application/json")
    public ResponseEntity<String> updateUser(@RequestBody User currentUser)
    {
        User user = userService.findById(currentUser.getId());
        if (user==null) {
            return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
        }
        user.setId(currentUser.getId());
        user.setName(currentUser.getName());
        user.setCountry(currentUser.getCountry());
        userService.update(user);
        return new ResponseEntity<String>(HttpStatus.OK);
    }

    @DeleteMapping(value="/{id}", headers ="Accept=application/json")
    public ResponseEntity<User> deleteUser(@PathVariable("id") int id){
        User user = userService.findById(id);
        if (user == null) {
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        userService.deleteUserById(id);
        return new ResponseEntity<User>(HttpStatus.NO_CONTENT);
    }

    @PatchMapping(value="/{id}", headers="Accept=application/json")
    public ResponseEntity<User> updateUserPartial(@PathVariable("id") int id, @RequestBody User currentUser){
        User user = userService.findById(id);
        if(user ==null){
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }

        userService.updatePartially(currentUser, id);
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }
}

Bean class

package com.candidjava.spring.bean;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

    private int id;
    private String country;
    private String name;
    public User(){
        id=0;
    }
    public User(int id, String name, String country){
        this.id = id;
        this.name = name;
        this.country = country;
    }
    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 getCountry() {
        return country;
    }

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

    public String toString()
    {
        return"name:"+name;
    }

}

Service Interface

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
    public void createUser(User user);
    public List<User> getUser();
    public User findById(int id);
    public void update(User user);
    public void deleteUserById(int id);
    public void updatePartially(User user, int id);
}

Service Implementation with dummy data

package com.candidjava.spring.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;

import com.candidjava.spring.bean.User;

@Service
public class UserServiceImp implements UserService {

    private static List<User> users;

    static {
        users = dummyUsers();
    }

    public List<User> getUser() {
        // TODO Auto-generated method stub
        return users;
    }

    public User findById(int id) {
        // TODO Auto-generated method stub
        for (User user : users) {
            if (user.getId() == id) {
                return user;
            }
        }
        return null;
    }

    public void createUser(User user) {
        // TODO Auto-generated method stub
        users.add(user);
    }

    public void deleteUserById(int id) {
        // TODO Auto-generated method stub
        Iterator<User> it = users.iterator();
        while (it.hasNext()) {
            User user = (User) it.next();
            if (user.getId() == id) {
                it.remove();
            }
        }
    }

    public void updatePartially(User currentUser, int id) {
        for (User user : users) {
            if (user.getId() == id) {
                if (currentUser.getCountry() != null) {
                    user.setId(id);
                    user.setCountry(currentUser.getCountry());
                }
                user.setName(user.getName());
                update(user);
            }
        }

    }

    public void update(User user) {
        // TODO Auto-generated method stub
        int index = users.indexOf(user);
        users.set(index, user);
    }

    private static List<User> dummyUsers() {
        // TODO Auto-generated method stub
        List<User> users = new ArrayList<User>();
        users.add(new User(14221, "John", "INDIA"));
        users.add(new User(14222, "Ben", "UK"));
        users.add(new User(14223, "Andrew", "INDIA"));
        users.add(new User(14224, "Samuael", "USA"));
        return users;
    }

}

 

Spring Boot Application.java

package com.candidjava;

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

}

 

Spring boot application.properties

logging.level.org.springframework.web=DEBUG

Maven dependencies 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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.candidjava.spring</groupId>
    <artifactId>Spring-Boot-RestCrud</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring-Boot-RestCrud Maven Webapp</name>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>


    </dependencies>

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

 

How to run

mvn spring-boot:run

 

Rest Endpoints

GET –> http://localhost:8080/user/get

Download

Spring boot rest curd example maven

References

Spring boot rest – Official website

 

Spring boot war tomcat – creating deployable war file

Step 1:  Extend SpringBootServletInitializer

The first step in producing a deployable war file is to provide a SpringBootServletInitializer subclass and override its configure method. This makes use of Spring Framework’s Servlet 3.0 support and allows you to configure your application when it’s launched by the servlet container.

package com.candidjava.spring.configuration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@ComponentScan(basePackages = "com.candidjava")
@Import({ SpringConfiguration.class })
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

}

 

Step 2 : Change packing to war

The next step is to update your build configuration so that your project produces a war file rather than a jar file.

Change pom.xml file packing type to war

 <packaging>war</packaging>

 

Step 3: Adding servlet container dependency

The final step in the process is to ensure that the embedded servlet container doesn’t interfere with the servlet container to which the war file will be deployed. To do so, you need to mark the embedded servlet container dependency as provided. spring boot without embedded tomcat, creates deployable war.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

 

To run this example use use maven goal as

mvn clean package

 

Download example spring-boot-deployable-war