spring boot Archives - Ebhor.com Read The Latest Post Java, Css, Html, Php learning articles Fri, 22 Sep 2023 09:45:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 https://www.ebhor.com/wp-content/uploads/2021/05/ebhor_logo_100x.jpg spring boot Archives - Ebhor.com 32 32 SpringBoot JPA @OneToMany Mapping : Fetch data from tables https://www.ebhor.com/springboot-onetomany-mapping-example/ Fri, 22 Sep 2023 11:24:00 +0000 https://www.ebhor.com/?p=13785 SpringBoot JPA @OneToMany Mapping as name says we will see one to many mapping in SpringBoot and JPA. First see the ER Diagram SpringBoot JPA @OneToMany Mapping ER Diagram Following is the Entity Relationship Diagram for user, user_mails and user_mobiles table. One user can have multiple mail ids. So this is a one to many ... Read more

The post SpringBoot JPA @OneToMany Mapping : Fetch data from tables appeared first on Ebhor.com.

]]>
SpringBoot JPA @OneToMany Mapping as name says we will see one to many mapping in SpringBoot and JPA.

First see the ER Diagram

SpringBoot JPA @OneToMany Mapping ER Diagram

Following is the Entity Relationship Diagram for user, user_mails and user_mobiles table.

One user can have multiple mail ids.

So this is a one to many relation.

similarly one user can have multiple mobile numbers.

This is also one to many mapping.

user’s id in user table is

Fig: Entity Relationship Diagram

Tools/Technology used

  1. Spring Boot 2.2
  2. JPA
  3. Eclipse IDE
  4. MySQL Database

SpringBoot JPA @OneToMany Mapping Directory Structure

SpringBoot  JPA @OneToMany Mapping Project Directory Structure
Fig: Project Directory Structure

To build project we used maven and included

  1. spring-boot-starter-web
  2. spring-boot-starter-data-jpa
  3. mysql-connector-java

You can also use spring Initializr to generate POM.xml

POM.xml


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.7.2
		 
	
	com.ebhor
	mvc
	0.0.1-SNAPSHOT
	war
	Spring Crud
	Spring CRUD Example
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			org.springframework.boot
			spring-boot-starter-tomcat
			provided
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			mysql
			mysql-connector-java
			runtime
		
		
	
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

Application.properties file configuration

MySQL database is used.

Configuration with MySQL is as specified below

spring.datasource.url=jdbc:mysql://localhost:3306/ebhor
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

Entities

We have created three entity files User, UserMail and UserMobile.

Tables and columns are mapped in entity file.

User.java

To access multiple mail and mobile numbers user is mapped with UserMail and UserMobile entities.

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set userMails = new HashSet(0);

@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set userMobiles = new HashSet(0);

@oneToMany mapping is used and few parameters are also used.

  1. mappedBy- a property name in userMails. Based on this property matching oneToMany mapping will be performed.
  2. cascade- Transactions that are performing on table will also perform on mapped table or not.
  3. fetch – specifies when to access mapped data from join table
package com.ebhor.crud.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "user")
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private int id;
	@Column(name = "name", nullable = false)
	private String name;
	@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
	private Set userMails = new HashSet(0);
	@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
	private Set userMobiles = new HashSet(0);
	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 Set getUserMails() {
		return userMails;
	}
	public void setUserMails(Set userMails) {
		this.userMails = userMails;
	}
	public User(int id, String name, Set userMails) {
		super();
		this.id = id;
		this.name = name;
		this.userMails = userMails;
	}
	public User() {
		super();
	}
	public Set getUserMobiles() {
		return userMobiles;
	}
	public void setUserMobiles(Set userMobiles) {
		this.userMobiles = userMobiles;
	}
}

UserMail.java

@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id")
@JsonIgnore
private User user;

Here User Object is mapped as Many to one.

The @JoinColumn specified based on which (user_mail) column it will perform join and fetch data.

@JsonIgnore- This will ignored the json result and prevent the loop.

package com.ebhor.crud.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name = "user_mails")
public class UserMail {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;

	@Column(name = "email", nullable = false)
	private String email;

	@ManyToOne(fetch = FetchType.LAZY, optional = false)
	@JoinColumn(name = "user_id")
	@JsonIgnore
	private User user;

	public UserMail() {
		super();
	}

	public UserMail(int id, String email, User user) {
		super();
		this.id = id;
		this.email = email;
		this.user = user;
	}

	public int getId() {
		return id;
	}

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

	public String getEmail() {
		return email;
	}

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

	public User getUser() {
		return user;
	}

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

}

UserMobiles

package com.ebhor.crud.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Entity
@Table(name = "user_mobiles")
public class UserMobile {

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

	@Column(name = "mobile_no", nullable = false)
	private String mobileNo;

	@ManyToOne(fetch = FetchType.LAZY, optional = false)
	@JoinColumn(name = "user_id")
	@JsonIgnore
	private User user;

	public UserMobile() {

	}

	public UserMobile(int id, String mobileNo, User user) {
		super();
		this.id = id;
		this.mobileNo = mobileNo;
		this.user = user;
	}

	public int getId() {
		return id;
	}

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

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public User getUser() {
		return user;
	}

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

}

UserDAO.java

UserDAO is responsible for fetching data from database.

package com.ebhor.crud.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.ebhor.crud.entity.User;
@Repository
public interface UserDAO extends CrudRepository{
}

UserService.java

package com.ebhor.crud.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ebhor.crud.dao.UserDAO;
import com.ebhor.crud.entity.User;
@Service
public class UserService {
	@Autowired
	UserDAO dao;
	public Iterable getUsers(){
		return dao.findAll();
	}
}

UserController.java

Here we have used RestController to show data on index position

package com.ebhor.crud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ebhor.crud.entity.User;
import com.ebhor.crud.service.UserService;
@RestController
public class UserController {
	@Autowired
	UserService service;
	
	@GetMapping("/")
	public Iterable users(){
		return service.getUsers();
	}
}

Result

On running above project we will get following data.

Result of @OneToMany Mapping
Fig: Result of @OneToMany Mapping

Read More

Angular Spring Boot Showing Data In Table

The post SpringBoot JPA @OneToMany Mapping : Fetch data from tables appeared first on Ebhor.com.

]]>
Angular Spring Boot showing data in table https://www.ebhor.com/angular-spring-boot-showing-data-in-table/ Fri, 22 Sep 2023 04:01:00 +0000 https://www.ebhor.com/?p=13590 Here we will use Angular and Spring boot to show data in HTML table. Spring boot To start a spring project go to https://start.spring.io/ For this project we selected Click on generate to download spring boot project then extract then project zip file and move to your project location. Eclipse IDE is used to develop ... Read more

The post Angular Spring Boot showing data in table appeared first on Ebhor.com.

]]>
Here we will use Angular and Spring boot to show data in HTML table.

Spring boot

To start a spring project go to https://start.spring.io/

For this project we selected

  1. Java 1.8
  2. Spring Web
  3. Spring Data JPA
  4. MySQL Driver
Spring Initializer to start spring boot project
Fig: Spring Initializer to start spring boot project

Click on generate to download spring boot project then extract then project zip file and move to your project location.

Eclipse IDE is used to develop spring boot project.

How to import maven project in Eclipse

  1. Open Eclipse
  2. Click on File
  3. Click on import
  4. On select import wizard select Maven
  5. Click on existing maven Project
  6. Click on next
  7. Browse folder
  8. Click on finish

Now maven project is imported to eclipse.

Updation of project is required for that follw this steps

  1. Right click on project in project Explorer
  2. Select Maven Option
  3. Update Maven
Spring Boot Project Explorer
Spring Boot Project Explorer

ExampleApplication.java

package com.ebhor.example;

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

@SpringBootApplication
public class ExampleApplication {

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

}

POM.xml


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.7.2
		 
	
	com.ebhor
	mvc
	0.0.1-SNAPSHOT
	war
	mvc
	Spring MVC Example
	
		1.8
	
	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-data-jpa
		
		
			org.springframework.boot
			spring-boot-starter-tomcat
			provided
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			mysql
			mysql-connector-java
			runtime
		
	
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

Application.properties

Here we configured spring datasource to connect with MySql Database.

spring.datasource.url=jdbc:mysql://localhost:3306/ebhor
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

EmployeeController.java

EmployeeController is used to fetch employee list from EmployeeService and send it to client using RestController.

@CrossOrigin(origins = “http://localhost:4200”) annotation is used to allow access this url to angular project.

package com.ebhor.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ebhor.example.entity.Employee;
import com.ebhor.example.service.EmployeeService;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class EmployeeController {
	@Autowired
	EmployeeService employeeService;
	@GetMapping("/")
	public Iterable getEmployess() {
		return employeeService.getEmployees();
	}
}

Employee.java

This is an Employee entity class which maps with database table employee.

package com.ebhor.example.entity;

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

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

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private int id;
	@Column(name = "name", nullable = false)
	private String name;
	@Column(name = "designation", nullable = false)
	private String designation;
	@Column(name = "mobileno", nullable = false)
	private String mobileNo;
	@Column(name = "mailid", nullable = false)
	private String mailId;
	@Column(name = "department", nullable = false)
	private String department;

	public Employee() {
	}

	public Employee(int id, String name, String designation, String mobileNo, String mailId, String department) {
		super();
		this.id = id;
		this.name = name;
		this.designation = designation;
		this.mobileNo = mobileNo;
		this.mailId = mailId;
		this.department = department;
	}

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

	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 getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String getMailId() {
		return mailId;
	}

	public void setMailId(String mailId) {
		this.mailId = mailId;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

}

EmployeeService.java

EmployeeServices fetch data from EmployeeDAO and pass to EmployeeController

package com.ebhor.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ebhor.example.dao.EmployeeDAO;
import com.ebhor.example.entity.Employee;
@Service
public class EmployeeService {
	@Autowired
	public EmployeeDAO employeeDAO;
	public Iterable getEmployees() {
		return employeeDAO.findAll();
	}
}

EmployeeDAO.java

Interface EmployeeDAO extends to CrudRepository which provice access to database table.

package com.ebhor.example.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.ebhor.example.entity.Employee;
@Repository
public interface EmployeeDAO extends CrudRepository{
}

To test our spring boot project you can call url using browser or Postman API

Postman API
Fig: Postman API

Angular Project

Visual studio code IDE is used to develop this project.

npm -v is 8.5.5
ng –version
Package and Version
@angular-devkit/architect 0.1303.7 (cli-only)
@angular-devkit/core 13.3.7 (cli-only)
@angular-devkit/schematics 13.3.7 (cli-only)
@schematics/angular 13.3.7 (cli-only)

Angular Commands

  1. To create new project => ng new angularapp1
  2. Generate service => ng g s employee
  3. Start server => ng serve
Angular Project Explorer
Fig: Angular Project Explorer

index.html

Remove all existing body content.

add Bootstrap CDN in head section




  
  Angularapp1
  
  
  
  


  

app.module.ts

Here HttpClientModule is added in imports.

import { NgModule } from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Employee.ts

This file contains employee interface that is having all fields of employee.

export interface Employee{
    id: number,
    name: string,
    designation:string,
    mobileNo:string,
    mailId:string,
    department:string
}

employee.service.ts

This file contains a method getEmployees() to get the employee data from specified url.

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { Employee } from './employee';
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  private url = "http://localhost:8080/"
  constructor(private http: HttpClient) { }
  getEmployees(): Observable {
    return this.http.get(this.url)
      .pipe(
        retry(2),
        catchError(this.handleError)
      );
  }
  private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, body was: `, error.error);
    }
    // Return an observable with a user-facing error message.
    return throwError(() => new Error('Something bad happened; please try again later.'));
  }
}

app.component.ts

This fill access the EmployeeService class and get data of Employee to employess variable

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public employees: any;
  constructor(private _employeeService: EmployeeService) { }
  ngOnInit(): void {
    this.employees = this._employeeService.getEmployees()
      .subscribe(data => this.employees = data);
  }


}

app.component.html:

This is HTML file to show employee data

ngFor is used to loop employees and interpolation is used to show data or employee

Employee details are

Id Name Designation MobileNo MailId Department
{{employee.id}} {{employee.name}} {{employee.designation}} {{employee.mobileNo}} {{employee.mailId}} {{employee.department}}

Afterexecuting you will get following output.

Angular Spring boot Showing data in table
Fig: showing Employee data using spring boot and angular

Hope you understand how to use Angular and Spring boot to show data in HTML table..

Read More

Angularjs select : ng-repeat ng option default multiple select selected value

The post Angular Spring Boot showing data in table appeared first on Ebhor.com.

]]>
Spring Boot Security Form Authentication In Memory Users https://www.ebhor.com/spring-boot-security-form-authentication-in-memory-users/ Mon, 24 Jul 2023 06:57:30 +0000 https://www.ebhor.com/?p=16346 Spring Boot Security is a module in the Spring Boot framework that handles authentication, authorization, and other security aspects in web applications. It provides features like user management, CSRF protection, and security filters to ensure robust application security with minimal configuration and coding effort. The key components of Spring Boot Security include: Authentication: Handles user ... Read more

The post Spring Boot Security Form Authentication In Memory Users appeared first on Ebhor.com.

]]>
Spring Boot Security is a module in the Spring Boot framework that handles authentication, authorization, and other security aspects in web applications.

It provides features like user management, CSRF protection, and security filters to ensure robust application security with minimal configuration and coding effort.

The key components of Spring Boot Security include:

  1. Authentication: Handles user identity verification using form-based login, HTTP Basic, and OAuth.
  2. Authorization: Defines access control rules based on roles and permissions to restrict user actions.
  3. Security Filters: Intercept and enforce security rules for incoming requests.
  4. User Management: Provides options to manage user details and passwords.
  5. CSRF Protection: Prevents Cross-Site Request Forgery attacks.
  6. Session Management: Handles user sessions and concurrent session control.
  7. Event Logging: Logs security-related events for auditing and monitoring.

Project Explorer

TestController.java

package com.example.demo.controller;

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

@RestController
public class TestController {

	@RequestMapping("/info")
	public String info() {
		return "This is a info page";
	}

	@RequestMapping("/")
	public String user() {
		return "This is a home page";
	}

	@RequestMapping("/teacher")
	public String teacher() {
		return "This is a teacher page";
	}

	@RequestMapping("/admin")
	public String home() {
		return "This is a admin page";
	}

}

The @RequestMapping("/info") annotation is used to map the info() method to handle HTTP requests with the URL path “/info”.

Similarly, there are other methods like user(), teacher(), and home() which are also annotated with @RequestMapping and mapped to different URL paths (“/”, “/teacher”, and “/admin” respectively).

SecurityConfiguration.java

package com.example.demo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
		httpSecurity.csrf().disable().authorizeHttpRequests()
		.requestMatchers("/info").permitAll()
				.requestMatchers("/teacher").hasRole("TEACHER")
				.requestMatchers("/admin").hasRole("ADMIN")
				.anyRequest().authenticated().and().formLogin();
		return httpSecurity.build();
	}

	@Bean
	public InMemoryUserDetailsManager userDetailsService() {
		// InMemoryUserDetailsManager (see below)
		UserDetails user1 = User.withUsername("user1").password(passwordEncoder().encode("password")).roles("USER")
				.build();

		UserDetails user2 = User.withUsername("user2").password(passwordEncoder().encode("password")).roles("TEACHER")
				.build();

		UserDetails user3 = User.withUsername("user3").password(passwordEncoder().encode("password")).roles("ADMIN")
				.build();

		return new InMemoryUserDetailsManager(user1, user2, user3);
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

}

The class is annotated with @Configuration, indicating that it is a configuration class that will define Spring beans and their dependencies.

“/info” URL allows all users access without authentication or authorization, providing unrestricted access to the page.

“/teacher” URL is limited to authenticated users with the “TEACHER” role, granting access only to those with appropriate authorization.

“/admin” URL is restricted to authenticated users having an “ADMIN” role, ensuring only authorized users can access this page.

Any URL requests except “/info”, “/teacher”, and “/admin” require authentication; users must log in to access other parts.

DemoApplication.java

package com.example.demo;

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



@SpringBootApplication
public class DemoApplication {

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

}

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.1</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Result

The post Spring Boot Security Form Authentication In Memory Users appeared first on Ebhor.com.

]]>
Spring boot crud example with MySQL and Postman https://www.ebhor.com/spring-boot-crud-example-with-mysql/ Tue, 02 May 2023 04:01:00 +0000 https://www.ebhor.com/?p=15472 Here we are discussing the Spring boot crud example with MySQL that will include all basic operations few queries for JPA and check responsesProject using Postman. Project Explorer for Spring boot crud example with MySQL Starting Spring boot Project with Spring Initializer Open Spring Initializer Click on Generate it will download file. Open Eclipse IDE ... Read more

The post Spring boot crud example with MySQL and Postman appeared first on Ebhor.com.

]]>
Here we are discussing the Spring boot crud example with MySQL that will include all basic operations few queries for JPA and check responsesProject using Postman.

Project Explorer for Spring boot crud example with MySQL

Project Explorer: Spring Boot CRUD Project
Project Explorer: Spring Boot CRUD Project

Starting Spring boot Project with Spring Initializer

Open Spring Initializer

Spring Initializer create starting spring boot project
Fig: Spring Initializer creates starting spring boot project

Click on Generate it will download file.

Open Eclipse IDE -> File-> import->Existing Maven Project.

Then import the project from a specific directory.

Open Java Resources-> src/main/java

then create packages

com.univ.app.controller
com.univ.app.dao
com.univ.app.entity
com.univ.app.service

Creating MySql Database

We have created a user and password and given all privileges to that account. created a database and created a table student.

CREATE USER 'sspu_userx25'@'localhost' IDENTIFIED BY 'MV7GG5TV2312';
GRANT ALL ON *.* TO 'sspu_userx25'@'localhost';
create database sspu;
use sspu;
create table student(
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
roll_no bigint(20) unsigned NOT NULL,
fname varchar(100),
mname varchar(100),
lname varchar(30),
dob date,
admission_date date,
mail_id varchar(100),
mobile_no varchar(100),
semester varchar(100),
course varchar(100),
add_date timestamp DEFAULT CURRENT_TIMESTAMP,
primary key(id),
unique key(mobile_no),
unique key(mail_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

To connect with the database all properties are at application.properties available in src/main/resources

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/sspu
spring.datasource.username=sspu_userx25
spring.datasource.password=MV7GG5TV2312
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql: true

Creating Files in Spring Boot Project

Entity Class

inside the com.univ.app.entity create a Student class (Student.java)

This class contains all filed that are available in the database and also its mapping.

package com.univ.app.entity;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.Objects;

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

@Entity
@Table(name = "student")
public class Student {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id")
	private Long id;
	@Column(name = "roll_no", nullable = false)
	private long rollNo;
	@Column(name = "fname", nullable = false)
	private String firstName;
	@Column(name = "mname", nullable = false)
	private String middleName;
	@Column(name = "lname", nullable = false)
	private String lastName;
	@Column(name = "dob", nullable = false)
	private Date dob;
	@Column(name = "admission_date", nullable = false)
	private Date admissionDate;
	@Column(name = "mail_id", nullable = false)
	private String mailId;
	@Column(name = "mobile_no", nullable = false)
	private String mobileNo;
	@Column(name = "semester", nullable = false)
	private String semester;
	@Column(name = "course", nullable = false)
	private String course;
	@Column(name = "add_date")
	private Timestamp addDate;

	public Student() {

	}

	public Student(Long id, long rollNo, String firstName, String middleName, String lastName, Date dob,
			Date admissionDate, String mailId, String mobileNo, String semester, String course, Timestamp addDate) {
		super();
		this.id = id;
		this.rollNo = rollNo;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.dob = dob;
		this.admissionDate = admissionDate;
		this.mailId = mailId;
		this.mobileNo = mobileNo;
		this.semester = semester;
		this.course = course;
		this.addDate = addDate;
	}

	@Override
	public int hashCode() {
		return Objects.hash(addDate, admissionDate, course, dob, firstName, id, lastName, mailId, middleName, mobileNo,
				rollNo, semester);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		return Objects.equals(addDate, other.addDate) &amp;&amp; Objects.equals(admissionDate, other.admissionDate)
				&amp;&amp; Objects.equals(course, other.course) &amp;&amp; Objects.equals(dob, other.dob)
				&amp;&amp; Objects.equals(firstName, other.firstName) &amp;&amp; Objects.equals(id, other.id)
				&amp;&amp; Objects.equals(lastName, other.lastName) &amp;&amp; Objects.equals(mailId, other.mailId)
				&amp;&amp; Objects.equals(middleName, other.middleName) &amp;&amp; Objects.equals(mobileNo, other.mobileNo)
				&amp;&amp; rollNo == other.rollNo &amp;&amp; Objects.equals(semester, other.semester);
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", rollNo=" + rollNo + ", firstName=" + firstName + ", middleName=" + middleName
				+ ", lastName=" + lastName + ", dob=" + dob + ", admissionDate=" + admissionDate + ", mailId=" + mailId
				+ ", mobileNo=" + mobileNo + ", semester=" + semester + ", course=" + course + ", addDate=" + addDate
				+ "]";
	}

	public Long getId() {
		return id;
	}

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

	public long getRollNo() {
		return rollNo;
	}

	public void setRollNo(long rollNo) {
		this.rollNo = rollNo;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getMiddleName() {
		return middleName;
	}

	public void setMiddleName(String middleName) {
		this.middleName = middleName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Date getDob() {
		return dob;
	}

	public void setDob(Date dob) {
		this.dob = dob;
	}

	public Date getAdmissionDate() {
		return admissionDate;
	}

	public void setAdmissionDate(Date admissionDate) {
		this.admissionDate = admissionDate;
	}

	public String getMailId() {
		return mailId;
	}

	public void setMailId(String mailId) {
		this.mailId = mailId;
	}

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String getSemester() {
		return semester;
	}

	public void setSemester(String semester) {
		this.semester = semester;
	}

	public String getCourse() {
		return course;
	}

	public void setCourse(String course) {
		this.course = course;
	}

	public Timestamp getAddDate() {
		return addDate;
	}

	public void setAddDate(Timestamp addDate) {
		this.addDate = addDate;
	}

}

Controller Class

Create StudentController inside com.univ.app.controller as below

We have created basic methods to add, update, delete, and fetch the record, also included methods to fetch records based on semester and course and the user can also update few fields separately like mail id and mobileNo.

The rest controller is used to access the data with different mapping styles like GetMapping, PostMapping, PutMapping etc.

package com.univ.app.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
import com.univ.app.entity.Student;
import com.univ.app.service.StudentService;
@RestController
public class StudentController {
	@Autowired
	StudentService service;
	@PostMapping("/add-student")
	public Student saveStudent(@RequestBody Student student) {
		return service.saveStudent(student);
	}
	@PostMapping("/add-students")
	public Iterable<Student> saveStudent(@RequestBody Iterable<Student> students) {
		return service.saveStudent(students);
	}
	@PutMapping("/update-student")
	public Student updateStudent(@RequestBody Student student) {
		return service.saveorUpdateStudent(student);
	}
	@GetMapping("/students")
	public Iterable<Student> getStudents() {
		return service.getStudents();
	}
	@GetMapping("/student/{id}")
	public Optional<Student> getStudent(@PathVariable("id") long id) {
		return service.getStudent(id);
	}
	@GetMapping("/student-fname/{firstname}")
	public Iterable<Student> getStudentbyFirstName(@PathVariable("firstname") String firstName) {
		return service.getStudentByFirstName(firstName);
	}
	@GetMapping("/student-course/{course}")
	public Iterable<Student> getStudentByCourse(@PathVariable("course") String course) {
		return service.getStudentByCourse(course);
	}
	@GetMapping("/student-semester/{semester}")
	public Iterable<Student> getStudentBySemester(@PathVariable("semester") String semester) {
		return service.getStudentBySemester(semester);
	}
	@GetMapping("/student-update-mail/{id}/{emailId}")
	public int updateStudentMail(@PathVariable("emailId") String emailId, @PathVariable("id") Long id) {
		return service.UpdateEmailId(emailId, id);
	}
	@GetMapping("/student-update-mobile/{id}/{mobileNo}")
	public int updateStudentMobile(@PathVariable("mobileNo") String mobileNo, @PathVariable("id") Long id) {
		return service.updateMobileNo(mobileNo, id);
	}
	@DeleteMapping("/remove-student/{id}")
	public void deleteById(@PathVariable("id") long id) {
		service.deleteById(id);
	}
}

Service class

StudentService.java inside com.univ.app.service

@Service annotation is used to make it a service class and dao is autowired to interact with StudentDAO.

package com.univ.app.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.univ.app.dao.StudentDAO;
import com.univ.app.entity.Student;
@Service
public class StudentService {
	@Autowired
	StudentDAO dao;
	public Student saveStudent(Student student) {
		return dao.save(student);
	}
	public Iterable<Student> saveStudent(Iterable<Student> students) {
		return dao.saveAll(students);
	}
	public Student saveorUpdateStudent(Student student) {
		Optional<Student> fetched = dao.findById(student.getId());
		Student s = fetched.get();
		s.setFirstName(student.getFirstName());
		s.setMiddleName(student.getMiddleName());
		s.setLastName(student.getLastName());
		s.setDob(student.getDob());
		s.setAdmissionDate(student.getAdmissionDate());
		s.setMailId(student.getMailId());
		s.setMobileNo(student.getMobileNo());
		s.setSemester(student.getSemester());
		s.setCourse(student.getCourse());
		s.setSemester(student.getSemester());
		return dao.save(s);
	}
	public Iterable<Student> getStudents() {
		return dao.findAll();
	}
	public Optional<Student> getStudent(long id) {
		return dao.findById(id);
	}
	public Iterable<Student> getStudentByFirstName(String firstName) {
		return dao.findStudentByFisrtName(firstName);
	}
	public Iterable<Student> getStudentByCourse(String course) {
		return dao.findStudentByCourse(course);
	}
	public Iterable<Student> getStudentBySemester(String semester) {
		return dao.findStudentBySemester(semester);
	}
	public void deleteById(long id) {
		dao.deleteById(id);
	}
	public int UpdateEmailId(String emailId, Long id) {
		return dao.updateEmailid(emailId, id);
	}
	public int updateMobileNo(String mobileNo, Long id) {
		return dao.updateMobileNo(mobileNo, id);
	}
}

DAO class

@Repository annotation is used to access data from a database.

StudentDAO extends JPARepositiiry.

Created Query for finding students by first name, course, and semester also created query for updating email and mobileNo.

package com.univ.app.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.univ.app.entity.Student;
import jakarta.transaction.Transactional;
@Repository
public interface StudentDAO extends JpaRepository<Student, Long> {
	@Query("SELECT s FROM Student s WHERE s.firstName = ?1")
	Iterable<Student> findStudentByFisrtName(String firstName);
	@Query("SELECT s FROM Student s WHERE s.course = ?1")
	Iterable<Student> findStudentByCourse(String course);
	@Query("SELECT s FROM Student s WHERE s.semester = ?1")
	Iterable<Student> findStudentBySemester(String semester);
	@Transactional
	@Modifying
	@Query("UPDATE Student s set s.mailId = ?1 where s.id=?2")
	int updateEmailid(String emailId, long id);
	@Transactional
	@Modifying
	@Query("UPDATE Student s set s.mobileNo = ?1 where s.id=?2")
	int updateMobileNo(String mobileNo, long id);
}

Checking Rest API with Postman

open postman and call APIs created in the controller. We called a few APIs as below.

Add Student API call

Spring boot postman add API test
Spring boot Postman add API test

Get a Student with id

Update User Details

Similar way you can test all other APIs

Read More

Angular Spring Boot showing data in table

SpringBoot JPA @OneToMany Mapping : Fetch data from tables

The post Spring boot crud example with MySQL and Postman appeared first on Ebhor.com.

]]>