Primary key as composite key in spring boot ?
Pages
- Interview Topics
- Java Collections
- Stream API
- Java 8 New Features
- Exception Handling
- Multithreading
- Executors
- Java Interview
- Junit In Java
- Kafka Tutorial
- Data Structure Interview
- Memory Management In Java
- ClassLoader In Java
- Swagger Integration
- Spring
- Spring Cloud
- Spring Security
- Spring Boot
- Spring Bean Scopes
- Spring Boot Security
- Mysql Database
- Hibernate
- Transaction Management
- Spring JdbcTemplate
- JNDI in java
- Spring Data JPA
- Java Programming Interview
- Agile Scrum
- Logger - Log4j
- AWS Interview
- Linux Commands
- Git Commands
- Jenkins
- Gang Of Four Design Patterns
- Code Review
- Tech Lead Interview
- Performance Of Java Application
- Effort Estimation In Project
- Build And Release Interview
- Documents Required In Software Development
- Roles And Responsibilities Of Technical Lead
Search
Saturday, March 25, 2023
Friday, May 20, 2022
Thursday, March 31, 2022
Sunday, December 19, 2021
Spring Security Interview Questions
Q:- What are some essential features of Spring Security?
Q:- Explain Spring Security Architecture using Spring Boot?
Q:- What is Spring security authentication and authorization?
Q:- What is principal in spring security?
The principal in an interface it represents the abstract notion of a principal, which can be used to represent any entity, such as an individual, a corporation, and a login id.
or we can say, The principal is the currently logged in user. However, we can retrieve it through the security context which is bound to the current thread and as such it's also bound to the current request and its session.
The Spring Security principal can only be retrieved as an Object and needs to be cast to the correct UserDetails instance:
The principal can be defined directly as a method argument.
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String getUserName(Principal principal) {
return principal.getName();
}
}
Alternatively, we can also use the authentication token:
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String getUserName(Authentication authentication) {
return authentication.getName();
}
}
Q:- Explain SecurityContextHolder, SecurityContext and Authentication Objects?
- SecurityContextHolder
- SecurityContext
- Authentication Objects
Q:- Explain AuthenticationManager, ProviderManager and AuthenticationProviders?
public interface AuthenticationManager {
Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
ProviderManager: ProviderManager is the default implementation of AuthenticationManager. It delegates the authentication process to a list of AuthenticationProvider objects.public class ProviderManager
extends Object
implements AuthenticationManager, MessageSourceAware, InitializingBeanAuthenticationProvider:public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
}public class AuthenticationManagerBuilder
extends AbstractConfiguredSecurityBuilder<AuthenticationManager,AuthenticationManagerBuilder>
implements ProviderManagerBuilder<AuthenticationManagerBuilder>
Q:-What is OAuth2 Authorization code grant type? How to implement it using Spring Boot Security?
Q:-Using Spring Boot Security how to refresh expired JSON Web Token?
Q:-What is JWT ? How to implement it using Spring Boot Security
Q:-What is OAuth2 Client Credentials Grant? How to implement it using Spring Boot Security
Q:-What is OAuth2 Password Grant? How to implement it using Spring Boot Security?
Q:- What do you mean by basic authentication?
Q:- What do you mean by digest authentication?
Q:-What do you mean by session management in Spring Security?
- SessionManagementFilter.
- SessionAuthneticationStrategy
With these two, spring-security can manage the following security session options:
- Session timeouts (amount of time a user can remain inactive on a website before the site ends the session.)
- Concurrent sessions (the number of sessions that an authenticated user can have open at once).
- Session-fixation (an attack that permits an attacker to hijack a valid user session).
Q:- Explain SecurityContext and SecurityContext Holder in Spring security.
Q:- Explain spring security OAuth2.
In OAuth2, There are four roles are available as shown below:
- Resource Owner/User:
- Client:
- Authorization Server:
- Resource Server:
Q:- What do you mean by OAuth2 Authorization code grant type?
Q:- What is method security and why do we need it?
Q:- What do you mean by HASHING in spring security?
Q:- Explain salting and its usage.
Q:- What is PasswordEncoder?
Q:- Explain AbstractSecurityInterceptor in spring security?
- FilterSecurityInterceptor:
- MethodSecurityInterceptor:
Q:- Is security a cross-cutting concern?
Answer: Yes
- Logging and tracing
- Transaction management
- Security
- Caching
- Error handling
- Performance monitoring
- Custom Business Rules
Q:- What is SpEL (Spring Expression Language)?
Q:- Name security annotations that are allowed to use SpEL.
Some security annotations that are allowed to use SpEL include:
- @PreAuthorize
- @PreFilter
- @PostAuthorize
- @PostFilter
Q:- Explain what is AuthenticationManager in Spring security.
Q:- Explain what is ProviderManager in Spring security.
Q:- What is JWT?
Q:- What is Spring Security Filter Chain?
Q:- Explain how the security filter chain works.
Q:- Name some predefined filters used in spring security and write their functions.
- SecurityContextPersistenceFilter:
- ConcurrentSessionFilter:
- UsernamePasswordAuthenticationFilter:
- ExceptionTranslationFilter:
- FilterSecurityInterceptor:
Q:- What do you mean by principal in Spring security?
Q:- Can you explain what is DelegatingFilterProxy in spring security?
Q:- Can you explain what is FilterChainProxy in spring security?
Q:- What is the intercept-url pattern and why do we need it?
Q:- Does order matter in the intercept-url pattern? If yes, then in which order should we write it?
Q:- State the difference between ROLE_USER and ROLE_ANONYMOUS in a spring intercept-url configuration.
- ROLE_USER:
- ROLE_ANONYMOUS:
Q:- State the difference between @PreAuthorize and @Secured in Spring security.
Q:- State the difference between @Secured and @RolesAllowed.
Q:-How to configure Spring Security using Spring Boot?
Q:-How to create Custom Login Page using Spring Boot Security?
Q:-How to do authentication against database tables using Spring Boot Security?
Q:-How to configure Spring Security with in-memory configuration?
Q:-What is the use of Spring Boot Security AuthenticationHandler class?
Q:-How to configure DelegatingFilterProxy?
Q:-How to configure Spring Security using Spring MVC
Wednesday, December 8, 2021
Versioning Restful Services With Spring Boot
Q:- Why do we need Versioning for RESTful Web Services?
Q:- What are the versioning options that are available?
Q:- How do you implement Versioning for RESTful Web Services?
Sunday, August 1, 2021
Spring Boot Bootstrap Thymeleaf Rich Text Editor
Spring Boot + Bootstrap + Thymeleaf Rich Text Editor
Download Minimal Rich Text Editor With jQuery And FontAwesome - RichText
cms.html<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Rich Text Editor -->
<title>RichText example</title>
<!-- <link rel="stylesheet"
th:href="@{/assets/richtext/font-awesome.min.css}"> -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" th:href="@{/assets/richtext/site.css}">
<link rel="stylesheet" th:href="@{/assets/richtext/richtext.min.css}">
<script type="text/javascript"
th:src="@{/assets/richtext/jquery.min.js}"></script>
<script type="text/javascript"
th:src="@{/assets/richtext/jquery.richtext.min.js}"></script>
<script type="text/javascript"
th:src="@{/assets/richtext/jquery.richtext.js}"></script>
<script>
$(document).ready(function() {
$('.content').richText();
});
</script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar" aria-expanded="false"
aria-controls="navbar">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active"><a class="nav-link" href="#">Home
<span class="sr-only">(current)</span>
</a></li>
<li class="nav-item"><a class="nav-link" href="#">About</a></li>
<li class="nav-item"><a class="nav-link" href="#">Services</a>
</li>
<li class="nav-item"><a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<br>
<br>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div th:if="${param.success}">
<div class="alert alert-info">You've successfully content to
our awesome app!</div>
</div>
<h1>Content Management System</h1>
<form th:action="@{/cms}" th:object="${post}" method="post">
<div class="form-group">
<label for="title">Title:</label> <input type="text" id="title"
placeholder="Title" autocomplete="off" class="form-control"
th:field="*{title}" />
</div>
<div class="form-group">
<label for="content">Content:</label>
<textarea type="text" rows="4" class="content"
placeholder="Content" th:field="*{content}" autocomplete="off"></textarea>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
</div>
</div>
</div>
</body>
</html>
PostController.javaimport org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.stock.analysis.entities.Post;
/**
* Standard Layout System with Fragment Expressions usage example
*/
@Controller
public class CmsController {
@ModelAttribute("module")
public String module() {
return "post";
}
@ModelAttribute("post")
public Post post() {
return new Post();
}
@GetMapping("/cms")
public String cmsEditor(Model model) {
model.addAttribute("post", new Post());
model.addAttribute("title", "new Titla");
model.addAttribute("content", "Hello");
return "cms";
}
@PostMapping
public String save(Post post, Model model) {
model.addAttribute("post", post);
return "cms";
}
}
Post.javaimport javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@Entity
@Table(name = "post")
public class Post {
@Id
@ApiModelProperty(notes = "Title")
private String title;
@ApiModelProperty(notes = "Content")
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Wednesday, July 7, 2021
Saturday, April 4, 2020
Spring Boot API - Return Success Response
In this post i am going to demonstrate that how we should return success responce in Spring boot rest API.
@RestController
@RequestMapping("/api/user")
@Api(value = "user", description = "Rest API to get user", tags = "User API")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/users", method = RequestMethod.POST, produces = "application/json")
@ApiOperation(value = "Getting all user list", response = APISuccessResponse.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 401, message = "You are not authorized access the resource"),
@ApiResponse(code = 404, message = "The resource not found") })
public ResponseEntity<APISuccessResponse> getUsers() {
APISuccessResponse responce = null;
List<User> userList = null;
try {
userList = userService.getUsers();
responce = new APISuccessResponse(HttpStatus.OK, "get Users List", userList);
} catch (Exception e) {
responce = new APISuccessResponse(HttpStatus.OK, "get Users List", userList);
}
return new ResponseEntity<>(responce, HttpStatus.OK);
}
}
Output: API Response{
"status": "OK",
"message": "get Users List",
"responseStatus": "Success",
"statusCode": 0,
"responseCount": 2,
"responceObject": [
{
"id": 1,
"firstName": "Amit",
"lastName": "Kumar",
"email": "amit.kumar@abc.com",
"mobile": "9999993690",
"address": {
"houseNo": "123",
"state": "New Delhi",
"city": "Delhi",
"pinCode": "110068"
}
},
{
"id": 2,
"firstName": "Test",
"lastName": "Pathak",
"email": "tset.123@abc.com",
"mobile": "996633221155",
"address": {
"houseNo": "963",
"state": "Maharast",
"city": "Mumbai",
"pinCode": "258963"
}
}
]
}
APISuccessResponse.javapackage com.example.user.response;
import java.util.List;
import org.springframework.http.HttpStatus;
public class APISuccessResponse extends APIResponse {
/*
* Response object can be an array of object or single object
*/
Object responceObject;
public APISuccessResponse(HttpStatus status) {
super(status);
setResponseStatus("Success");
setStatusCode(0);
}
public APISuccessResponse(HttpStatus status, String message, Object responceObject) {
super(status, message);
this.responceObject = responceObject;
setResponseStatus("Success");
setStatusCode(0);
setResponseCount(responceObject instanceof List<?> ? ((List<?>) responceObject).size() : 1);
}
public APISuccessResponse(HttpStatus status, Object responceObject) {
super(status);
this.setResponceObject(responceObject);
}
public Object getResponceObject() {
return responceObject;
}
public void setResponceObject(Object responceObject) {
this.responceObject = responceObject;
}
}
APIResponse.java
package com.example.user.response;
import org.springframework.http.HttpStatus;
public class APIResponse {
/*
* Http Status code of response
*/
private HttpStatus status;
/*
* Responce Message
*/
private String message;
/*
* Response Status string:Success or Failure
*/
private String responseStatus;
/*
* Response Status code
*/
private int statusCode;
/*
* Number of returned objects
*/
private int responseCount;
public APIResponse(HttpStatus status) {
this.status = status;
}
public APIResponse(HttpStatus status, String message) {
this(status);
this.message = message;
}
/*
* this is required while deserializing test response to create object
*/
public APIResponse() {
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getResponseStatus() {
return responseStatus;
}
public void setResponseStatus(String responseStatus) {
this.responseStatus = responseStatus;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public int getResponseCount() {
return responseCount;
}
public void setResponseCount(int responseCount) {
this.responseCount = responseCount;
}
}
APIErrorResponse.javapackage com.example.user.response;
import java.time.LocalDateTime;
import org.springframework.http.HttpStatus;
public class APIErrorResponse extends APIResponse {
private LocalDateTime timestamp;
public APIErrorResponse(HttpStatus status, String message, int statusCode) {
super(status, message);
this.timestamp = LocalDateTime.now();
setStatusCode(statusCode);
setResponseStatus("error");
setResponseCount(0);
}
}
Thursday, January 2, 2020
Monday, August 5, 2019
Integrate H2 Database In Spring Boot
Q- What is the H2 database?
- H2 is one of the most popular in-memory databases written in Java.
- It is an Open Source, lightweight i.e around 1 MB only and Very fast in-memory database.
- It Supports Web Console like other databases.
- And Supports Standard SQL and JDBC API
Spring Boot provides excellent integration support for H2 using simple properties configuration.
Q- What is the use of h2 database? Or Why in memory(H2) database? Or How does h2 database work?
H2 is an open-source lightweight Java database. It can be embedded with Java applications or run in the client-server mode.
Mainly, H2 database can be configured to run as in-memory database, which means that data will not persist on the disk.
It is very useful in testing while we don't want to make any changes into real database. Or you are doing some POC(Proof of concept) before starting a your project or you are working on prototype. and we don't want to set up an actual database.
Q- What is H2 Console?
H2 provide support to see your database on web browser. or we can say that H2 console helps to access the database from a browser.
Q- How do I download H2 Database in spring boot application?
you don't need to download and setup this. you just need to add dependency for H2 Databse in pom.xml. Spring will Auto Configure the same.
Q- How do I restore my h2 database?
One you restart you application it will restart automatically. because it is created database while application start and gets destroyed on stopping or shutdown the application.
Q- How does h2 Database connect to spring boot application?
Go to https://start.spring.io/ to generate spring boot project with following.
Choose Group like com.javaiq.springboot.example
Choose Artifact like spring-boot-h2-database-jpa-hibernate
Choose following dependencies
- Web
- JPA
- H2
- DevTools
Go to : File -> Import -> Existing Maven Project.
Note:- you will see as below dependency in your pom.xml
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
H2 provides a web interface called H2 Console to check your data. To enable h2 console add as given below into the application.properties./src/main/resources/application.properties
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
Add Datasource into application.properties
# Datasourde details
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
http://localhost:8080/h2-consoleOr
http://localhost:8080/h2/
How to use H2 in unit testing:
First of all you need to add the dependencies for your database driver like if you are using ( MYSQL Database) then make the dependency for h2 test scoped.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
Wednesday, July 3, 2019
Spring Boot Multiple Datasources Configuration
- DataSource configuration
- EntityManagerFactory configuration
- TransactionManager configuration
<?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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>in.javaiq</groupId>
<artifactId>SpringBoot-Multiple-Datasources</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot-Multiple-Datasources</name>
<description>Spring Boot Multiple Datasources With Spring Data</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
</build>
</project>
Add below in application.properties here we are using two database company_db and employee_db using MYSQL database. As i have only MYSQL on my local. you can also use different database in same way.# For Datasources-1
spring.datasource.company.url=jdbc:mysql://localhost:3306/company_db
spring.datasource.company.jdbcUrl=${spring.datasource.company.url}
spring.datasource.company.username=root
spring.datasource.company.password=root
spring.datasource.company.platform=mysql
spring.datasource.company.driverClassName = com.mysql.jdbc.Driver
# For Datasources-2
spring.datasource.employee.url=jdbc:mysql://localhost:3306/employee_db
spring.datasource.employee.jdbcUrl=${spring.datasource.employee.url}
spring.datasource.employee.username=root
spring.datasource.employee.password=root
spring.datasource.employee.platform=mysql
spring.datasource.employee.driverClassName = com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
Create Model (JPA Entities) : Company.java and Employee.java
package in.javaiq.company.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;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "company")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false)
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 Company() {
}
public Company(String name) {
super();
this.name = name;
}
public Company(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Company [id=" + id + ", name=" + name + "]";
}
}
package in.javaiq.employee.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;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "employees")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false)
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee() {
}
public Employee(String name) {
super();
this.name = name;
}
public Employee(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + "]";
}
}package in.javaiq.company.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import in.javaiq.company.model.Company;
@Repository
public interface CompanyRepository extends CrudRepository<Company, Integer> {
}
package in.javaiq.employee.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import in.javaiq.employee.model.Employee;
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
}package in.javaiq.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableJpaRepositories(basePackages = "in.javaiq.company.repo", entityManagerFactoryRef = "companyEntityManagerFactory", transactionManagerRef = "companyTransactionManager")
public class CompanyDBConfig {
@Bean(name = "companyDataSource")
@ConfigurationProperties(prefix = "spring.datasource.company")
public DataSource customerDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "companyEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
@Qualifier("companyDataSource") DataSource dataSource) {
Map<String, Object> properties = new HashMap<String, Object>();
// properties.put("hibernate.hbm2ddl.auto", "update");
// properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return builder.dataSource(dataSource).properties(properties).packages("in.javaiq.company.model")
.persistenceUnit("db1").build();
}
@Bean(name = "companyTransactionManager")
public PlatformTransactionManager customerTransactionManager(
@Qualifier("companyEntityManagerFactory") EntityManagerFactory customerEntityManagerFactory) {
return new JpaTransactionManager(customerEntityManagerFactory);
}
}
package in.javaiq.config;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "in.javaiq.employee", entityManagerFactoryRef = "employeeEntityManagerFactory", transactionManagerRef = "employeeTransactionManager")
public class EmployeeDBConfig {
@Primary
@Bean(name = "employeeDataSource")
@ConfigurationProperties(prefix = "spring.datasource.employee")
public DataSource customerDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "employeeEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
@Qualifier("employeeDataSource") DataSource dataSource) {
Map<String, Object> properties = new HashMap<String, Object>();
// properties.put("hibernate.hbm2ddl.auto", "update");
// properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return builder.dataSource(dataSource).properties(properties).packages("in.javaiq.employee.model")
.persistenceUnit("db2").build();
}
@Primary
@Bean(name = "employeeTransactionManager")
public PlatformTransactionManager customerTransactionManager(
@Qualifier("employeeEntityManagerFactory") EntityManagerFactory customerEntityManagerFactory) {
return new JpaTransactionManager(customerEntityManagerFactory);
}
}
Create SpringBootMultipleDatasourcesApplication.java.
package in.javaiq;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import in.javaiq.company.model.Company;
import in.javaiq.company.repo.CompanyRepository;
import in.javaiq.employee.model.Employee;
import in.javaiq.employee.repo.EmployeeRepository;
@SpringBootApplication
@RestController
public class SpringBootMultipleDatasourcesApplication {
@Autowired
private CompanyRepository companyRepository;
@Autowired
private EmployeeRepository employeeRepository;
@PostConstruct
public void saveData() {
;
companyRepository
.saveAll(Stream.of(new Company("Company-1"), new Company("Company-2")).collect(Collectors.toList()));
employeeRepository.saveAll(
Stream.of(new Employee("Employee-1"), new Employee("Employee-2")).collect(Collectors.toList()));
}
@GetMapping("/getCompanyList")
public List<Company> getAllCompanys() {
List<Company> companyes = (List<Company>) companyRepository.findAll();
return companyes;
}
@GetMapping("/getEmployeeList")
public List<Employee> getAllEmployees() {
List<Employee> employeess = (List<Employee>) employeeRepository.findAll();
return employeess;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootMultipleDatasourcesApplication.class, args);
}
}
Tuesday, July 2, 2019
Spring Boot JdbcTemplate Example
<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.topjavatutorial.app</groupId>
<artifactId>SpringJDBC</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringJDBC</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.BUILD-SNAPSHOT</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-jdbc</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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
Add datasource details in application.properties file.
spring.datasource.name=jdbcTest
# Applicationn context name
server.contextPath=/springjdbc
# Here 'test' is the database name
#spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=none
#spring.datasource.initialize=false
#spring.datasource.url=jdbc:h2:file:~/jdbcTest;DB_CLOSE_ON_EXIT=FALSE;IFEXISTS=TRUE;DB_CLOSE_DELAY=-1;
#spring.jpa.hibernate.ddl-auto =update
Create SpringBootApp.java
package com.shubh.jdbctemplate.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
}
}
Create an Empoloyee class.
package com.shubh.jdbctemplate.example;
public class Employee {
private int empid;
private String name;
private int age;
private String email;
private String phone;
private String address;
public int getEmpId() {
return empid;
}
public void setEmpId(int id) {
this.empid = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Create EmployeeRowMapper to map "(ResultSet to Employee object"
package com.shubh.jdbctemplate.example;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class EmployeeRowMapper implements RowMapper {
public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
Employee employee = new Employee();
employee.setEmpId(rs.getInt("EMP_ID"));
employee.setName(rs.getString("NAME"));
employee.setAge(rs.getInt("AGE"));
employee.setEmail(rs.getString("email"));
employee.setAddress(rs.getString("address"));
employee.setPhone(rs.getString("telephone"));
return employee;
}
}
Create EmployeeDAO interface
package com.shubh.jdbctemplate.example;
import java.util.List;
public interface EmployeeDAO {
public String getEmployeeName(int id);
public List findAllEmployee();
// add other methods
//.......
//........
//.......
}
Create EmployeeDAOImpl implementation of EmployeeDAO. In the class i have written different way to use CRUD operation.
package com.shubh.jdbctemplate.example;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Repository
public class EmployeeDAOImpl implements EmployeeDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
// Way-1 insert data
public void addEmployee() {
// INSERT Employee data
String sqlInsertQuery = "INSERT INTO Employee (name, email, address, telephone) VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sqlInsertQuery, "TestUser00",
"testuseremail@gmail.com", "Test User Address", "011789632145");
}
// Way-2 insert data
public int insert(Employee employee) {
return jdbcTemplate.update("insert into Employee (id, name, age) "
+ "values(?, ?, ?)", new Object[] { employee.getEmpId(),
employee.getName(), employee.getAge() });
}
// Way-1 Update record
public void updateEmployee() {
// UPDATE Employee data
String sqlUpdateQuery = "UPDATE Employee set email=? where name=?";
jdbcTemplate
.update(sqlUpdateQuery, "test123@gmail.com", "Employee 101");
}
// Way-2 Update record
public int update(Employee employee) {
return jdbcTemplate.update("update Employee "
+ " set name = ?, age = ? " + " where id = ?", new Object[] {
employee.getName(), employee.getAge(), employee.getEmpId() });
}
// Way-1 delete record
public String deleteEmployee() {
// DELETE employee
try {
String sqlDeleteQuery = "DELETE FROM Employee where name=?";
jdbcTemplate.update(sqlDeleteQuery, "Employee 104");
} catch (DataAccessException exObj) {
exObj.printStackTrace();
}
return "Record has been deleted successfylly.";
}
// Way-2 delete record
public int deleteById(long id) {
return jdbcTemplate.update("delete from Employee where Emp_id=?",
new Object[] { id });
}
public List getEmployees() {
// get all employee list
String sqlSelectQuery = "SELECT name, email, address, telephone FROM Employee";
List listEmployees = jdbcTemplate.query(sqlSelectQuery,
new RowMapper() {
public Employee mapRow(ResultSet rs, int rowNum)
throws SQLException {
Employee employee = new Employee();
employee.setName(rs.getString("name"));
employee.setEmail(rs.getString("email"));
employee.setAddress(rs.getString("address"));
employee.setPhone(rs.getString("telephone"));
return employee;
}
});
return listEmployees;
}
public String getEmployeeName(int empId) {
String sql = "select name from employee where emp_id = ?";
String name = jdbcTemplate.queryForObject(sql, new Object[] { empId },
String.class);
return name;
}
// Way-1 to get single record
public Employee findByEmployeeId(int empId) {
String sql = "SELECT * FROM Employee WHERE EMP_ID = ?";
Employee employee = (Employee) jdbcTemplate.queryForObject(sql,
new Object[] { empId }, new EmployeeRowMapper());
return employee;
}
// Way-2 to get single record
public Employee findByEmployeeId2(int empId) {
String sql = "SELECT * FROM Employee WHERE EMP_ID = ?";
Employee employee = jdbcTemplate.queryForObject(sql,
new Object[] { empId }, new BeanPropertyRowMapper(
Employee.class));
return employee;
}
// Way-1 to get all employee records
public List findAllEmployee() {
String sql = "SELECT * FROM Employee";
List employeeList = new ArrayList();
List
Create EmployeeController
package com.shubh.jdbctemplate.example;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {
@Autowired
public EmployeeDAO dao;
@RequestMapping("/getAllEmployee")
public List getAllEmployee() {
List employee = dao.findAllEmployee();
return employee;
}
}
Sunday, June 30, 2019
Spring Boot JdbcTemplate Configuration
Step-1:- Add dependency into pom.xml (Spring boot jdbc & database dependency) .
<!-- Spring boot jdbc dependency -->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-jdbc</artifactid>
</dependency>
<!-- MySql dependency -->
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
</dependency>
Step-2:- Add Datasource details in application.properties file
spring.datasource.name=jdbcTest
# Applicationn context name
server.contextPath=/springjdbc
# Here 'test' is the database name
#spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=none
#spring.datasource.initialize=false
#spring.datasource.url=jdbc:h2:file:~/jdbcTest;DB_CLOSE_ON_EXIT=FALSE;IFEXISTS=TRUE;DB_CLOSE_DELAY=-1;
#spring.jpa.hibernate.ddl-auto = update
Step-3:- Now we can use JDBCTemplate object in DAO by using @Autowired annotation
@Autowired
private JdbcTemplate jdbcTemplate;
For more details :- See Spring Boot JdbcTemplate Example