Skip to main content

Posts

Showing posts with the label SpringBoot

SpringDataJPA : One to Many Mapping in Spring Boot Hibernate JPA with Spring Data

Also Read One To One Mapping Let's create two entities/domains Employee and Department such that they have the following relation between them. Department has-many Employees which means an Employee can belong to only one Department and a Department can have many Employee and Department is the owner of the relation between the two. Owner of the relation means that Owner can exist without the dependent entity but dependent entity cannot stay without the owner entity . Dependent Entity of Relationship will containes the 'foreign key' ID of the Owner entity . In this case, Address will contian the Employee Id in >its table as shown in the table structure below. So a Department can exist without Employee but an Employee cannot be there without a Department. If you on deleting an Employee, the Employee-Department mapping will be removed on deleting a Department, all the employees in the department should be deleted. Employee.java package com.ekiras.domain; import jav...

SpringDataJPA : One to one Mapping in Spring Boot Hibernate JPA with Spring Data

Also Read One To Many Mapping Let's create two classes Employee and Address , such that they have the following relation between them. Employee has-a Address which means a one-to-one mapping between the two and Employee is the owner of the relation. Owner of the relation means that Owner can exist without the dependent entity but dependent entity cannot stay without the owner entity. Dependent Entity of Relationship will containes the 'foreign key' ID of the Owner entity . In this case, Address will contian the Employee Id in its table as shown in the table structure below. This means that Employee can stay without an Address but Address cannot stay without the Employee. In even more simpler words, If employee is deleted his address should also be deleted, but if address is deleted employee should not be deleted. Employee.java package com.ekiras.domain; import javax.persistence.*; import java.util.Date; /** * @author ekiras */ @Entity public class Employee { ...

SpringDataJpa : How to override the domain mapping defined in Parent Entity class with MappedSuperclass

Points To Remember Your Parent class should be annotated with @MappedSuperclass . Follow the Tutorial : How to handle Inheritence with Entities to know how to wrap common properties of entities to a base class. To override any property you must a. Apply the @AttributeOverride annotation on the class that need to override the property b. set name property of @AttributeOverride as the name of the field in super class. c. set the column property of @AttributeOverride to override the column definition of the attribute. Let's say our Base class looks as follows package com.ekiras.domain.base; import javax.persistence.*; import java.util.Date; /** * @author ekiras */ @MappedSuperclass public abstract class BaseDomain { @Id @GeneratedValue (strategy = GenerationType.AUTO) protected long id; @Temporal (TemporalType.TIMESTAMP) protected Date dateCreated; @Temporal (TemporalType.TIMESTAMP) protected Date lastUpdated; @Override public String toString (...

SpringBoot : How to create a Filter in Spring Boot Application

Points To Remember Implement the class Filter . Add @Configuration  annotation to the class to register it as a filter bean. Call method  filterChain.doFilter(resquest,response)  to continue the request flow Call method sendError to send error, ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST); Call method sendRedirect to redirect request to error handler ((HttpServletResponse)response).sendRedirect("/errorUrl"); How to create a Filter in Spring Boot Application IN order to make a filter, we have create a class SecurityFilter view plain copy to clipboard print ? package  com.ekiras.filter;      import  org.springframework.core.Ordered;   import  org.springframework.core.annotation.Order;   import  org.springframework.stereotype.Component;      import  javax.servlet.*;   import  javax.servlet.http.HttpServletResponse;   import  ja...

SpringBoot : What is Spring Boot

Spring Boot : Introduction Spring Boot can be referred as Spring on Steroids.  Spring boot is a wrapper written over spring modules to allow users to create fast paced spring applications without doing the redundent configurations needed to setup the application. Features provided by Spring Boot CLI applications  - enables to create a single class application. Embedded Tomcat and Jetty Auto configurations for most of the libraries like mysql, mongo, amqp etc No Xml required for setup or configurations. Ability to package the application as both war and jar. Dependency Management using starter projects and BOM's. For example, When you create a spring application that needs Mysql database. We had to  declare the mysql connector dependency in build file. add the component scan to search the classes for mappings. map each entity/domain in xml files. Read data base configurations and create DataSource bean. add resource handlers to serve static content like css, js, images e...

Spring : Difference between @Autowired, @Inject and @Resource

Points To Remember @Inject is not a spring feature you need to include  javax inject dependency  in order to use @Inject. @Autowired is Spring annotation used to inject dependency just like @Inject. It use @Qualifier annotation to differentiate between the beans. @Resource is also Spring annotation, but it uses bean name to inject dependencies and differentiate between beans. Problem Statement :: Structure In order to show how @Autowired @Inject and @Resource annotations work  we will create 3 services Interface PersonService , this is the interface for all person related operations. Class EngineerService , this is the service that will do operations for engineer. Class ManagerService , this is the service that will do operations for manager. Here, both EngineerService and ManagerService implements PersonService.  Now we will try to add the services to a controller by different  ways to test how @Autowire , @Inject and @Resource will work. So the ...

SpringBoot : What are Profiles in Spring Boot Application

What are Profiles in Spring Boot Profiles can be seen as different environments in spring boot application. Suppose you are working on an application where you have different staging environments like Dev, QA, UAT, Production etc. So you will have different configurations for each environment, for this kind of applications what you need is having different values that can be switched depending upon some flags. In early days, people used to write configurations for all environments and comment the unused environments. But with Spring Boot we can do this without commenting any code by use of Profiles . Suppose we have database name configurations for our application as follows Dev     - ekiras_dev QA    - ekiras_qa UAT  - ekiras_uat Prod  - ekiras Now, we can use profiling in this case. How we will do it ? lets see Creating Profiles in Spring Boot  We will create different files for different environments and call then as profile in rest of the blog...

SpringBoot : How to display static html file in Spring boot MVC application

Points To Remember In order to serve static files like js, css, images etc ,all your files should be under the resources/static folder. Spring application can serve all the static files inside folders resources/static/ resources/public/ In order to serve html files from spring boot application  your html files should be under static/public folder you need to add view controller to serve html file How to display static html file in Spring boot MVC application Step 1 : Extend Class WebMvcConfigurerAdapter You should create a class that extends WebMvcConfigurerAdapter Your class should have  @Configuration annotation. You class should not have  @EnableMvc annotation. Override addViewControllers method and add your mapping. Override configurePathMatch method and update suffix path matching. view plain copy to clipboard print ? @Configuration    public   class  MvcConfigurer  extends  WebMvcConfigurerAdapter {      ...

SpringBoot : How to run Spring boot application to custom port

Points To Remember Default port for spring boot application is 8080. You can change the port number in the following ways from  application.properties command line arguments How to run Spring boot application to custom port In order to run a spring boot application on a custom port you can specify the port in application.properties. server.port=8090 If you are using environment specific properties file then you can define server.port  property in each of your properties file. You can alternatively set the port from command line arguments like below gradle -Dserver.port=8090 bootRun This will override any configuration of port given inside the properties file or application.yml file.

SpringSecurity : How to disable Session Creation for Stateless Authentication

How to disable Session Creation for Stateless Authentication We need to disable session creation for authenticating requests based on token based authentication. This can be easily configured by the following configurations. view plain copy to clipboard print ? package  com.ekiras.ss.security.config;      import  com.ekiras.ss.security.filter.TokenAuthenticationFilter;   import  org.springframework.context.annotation.Bean;   import  org.springframework.core.Ordered;   import  org.springframework.core.annotation.Order;   import  org.springframework.security.config.annotation.web.builders.HttpSecurity;   import  org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;   import  org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;   import  org.springframework.security.config.http.SessionC...

SpringSecurity : Authenticate User with Custom UserDetailsService

Points To Remember Create class that implement UserDetailsService and override loadUserByUsername() method. Throw UsernameNotFoundException if no user was found by username. Register this class as a bean by overriding WebSecurityConfigurerAdapter . Authenticate User with Custom UserDetailsService Step 1 : Create Entities for User and Role Create Entity User package com.ekiras.ss.domain; import javax.persistence.*; import java.util.Set; /** * @author ekiras */ @Entity public class User { @Id @GeneratedValue (strategy = GenerationType.AUTO) private long id; private String username; private String password; private boolean enabled; @ManyToMany (fetch = FetchType.EAGER,cascade = CascadeType.ALL) @JoinTable (joinColumns = @JoinColumn (name = "user_id" ),inverseJoinColumns = @JoinColumn (name = "role_id" )) private Set<role> roles; // GETTERS and SETTERS } Create Entity Role package com.ekiras.ss.domain; ...

SpringSecurity : Configure JDBC Authetication using MYSQL Query

Create Database Schema and tables First we will create a Database Schema as shown in the image below. We have to create 3 Tables in database. user - to hold the user data. role - to hold the data of roles that a user can have. user_roles - to hold the mapping of user and roles. Configure JDBC Authetication using MYSQL Query. Step 1 : Add the Dependencies compile('org.springframework.boot:spring-boot-starter-data-jpa') runtime('mysql:mysql-connector-java') Step 2 : Add the Datasource properties spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost/demo_ss spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.maxActive=10 spring.datasource.max-idle=4 spring.datasource.min-idle=2 spring.datasource.test-while-idle=true spring.datasource.test-on-borrow=true spring.datasource.validation-query=SELECT 1 spring.datasource.time-between-eviction-runs-millis=60000 ...