0% found this document useful (0 votes)
29 views16 pages

CRUD Operation Using Spring Boot

Uploaded by

devappsachindra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views16 pages

CRUD Operation Using Spring Boot

Uploaded by

devappsachindra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

CRUD OPERATION WITH SPRING BOOT

Pragyanand Singh
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

Table of Contents
1. CRUD Operation using spring boot .......................................................................................................................................................................................... 2
1) Employee class ..................................................................................................................................................................................................................... 2
2) Repository ............................................................................................................................................................................................................................ 3
3) Controller Class 1 for view ................................................................................................................................................................................................... 4
4) Controller Class 2 for postman ............................................................................................................................................................................................ 7
5) Rest Controller Advice's ....................................................................................................................................................................................................... 9
6) User defined Runtime Exception ....................................................................................................................................................................................... 10
7) Main class........................................................................................................................................................................................................................... 11
8) Page for Add Employee details .......................................................................................................................................................................................... 14
9) Home page to view all employee details ........................................................................................................................................................................... 12
10) Page for update Employee’s details............................................................................................................................................................................... 15

P a g e 1 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

1. CRUD Operation using spring boot


1) Employee class
@Data
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
@NotNull(message = "should not be blank") Commented [PS1]: @NotNull Char Sequence, Collection,
// @Size(min = 3, max = 8, message = "size is 3-8") Map, or Array object can be validated with this and they
@Pattern(regexp = "^[a-zA-Z]{6,12}$", message = "username must be of 6 to 12 length with no special characters should not be null but can be empty
and numbers") @NotEmpty Char Sequence, Collection, Map, or Array
/* object can be validated with this and they should not be null
* @Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{4,12}$", and not empty
* message = "password must be min 4 and max 12 length containing atleast 1 uppercase, 1 lowercase, 1 special @NotBlank Char Sequence, Collection, Map, or Array
* character and 1 digit ") objects can be validated with this and they should not be
*/ null and not empty and not blank
String name; @Min Given Minimum value has to get satisfied
// @Size(min = 10, max = 10, message = "size is 10") //not allowed for number @Max Given Maximum value has to get satisfied
long mob; @Size Field size should be less than or greater than the
@Min(value = 10000, message = "salary should be > 10000") specified field size
@Max(value = 100000, message = "should be < 100000") @Email Email can be validated with this
double salary; @Pattern Given RegEx Pattern has to be satisfied
}

Other Annotation:

• @DateTimeFormat(pattern = "yyyy-MM-dd")
• @Positive and @PositiveOrZero apply to numeric values and validate that they are strictly positive, or positive including 0.
• @Negative and @NegativeOrZero apply to numeric values and validate that they are strictly negative, or negative including 0.
• @Past and @PastOrPresent validate that a date value is in the past or the past including the present; can be applied to date types including those
added in Java 8.
• @Future and @FutureOrPresent validate that a date value is in the future, or in the future including the present.

P a g e 2 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

2) Repository
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface EmpRepository extends JpaRepository<Employee, Integer> {


public List<Employee> findByName(String name); Commented [PS2]: The Spring Data Repository will auto-
generate the implementation based on the name we
@Query(value = "select mob from employee where name=:name", nativeQuery = true) provided it.
public Long noByName(@Param("name") String name);
} Commented [PS3]: @Query annotation in Spring Data JPA
to execute both JPQL and native SQL queries.
Commented [PS4]: @param Annotation to bind
• save(…) – save an Iterable of entities. Here, we can pass multiple objects to save them in a batch method parameters to a query via a named parameter
• findOne(…) – get a single entity based on passed primary key value
• findAll() – get an Iterable of all available entities in database
• count() – return the count of total entities in a table
• delete(…) – delete an entity based on the passed object
• exists(…) – verify if an entity exists based on the passed primary key value

P a g e 3 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

3) Controller Class 1 for view


@Controller
@RequestMapping("/employee") Commented [PS5]: It is used to map the web requests. It
public class WebController { has many optional elements like consumes, header,
@Autowired method, name, params, path, produces, and value. We use
EmpRepository repo; it with the class as well as the method.

@RequestMapping(method = RequestMethod.GET) Commented [PS6]: @Autowired annotation, the spring


public ModelAndView getallEmp(ModelAndView mv) { container auto-wires the bean by matching data-type
List<Employee> emp = repo.findAll(); Commented [PS7]: Model is an interface while
mv.addObject("Emp", emp); ModelMap is a class. ModelAndView is just a container
mv.setViewName("index"); for both a ModelMap and a View object. It allows a
return mv; controller to return both as a single value.
}

@PostMapping("/search") Commented [PS8]: It maps the HTTP POST requests on


the specific handler method. It is used to create a web
public String searchEmp(@RequestParam(value = "name") String name, Model m) { service endpoint that creates It is used instead of
List<Employee> emp = repo.findByName(name); using: @RequestMapping(method = RequestMethod.POST)
System.out.println(emp.isEmpty());
if (emp.isEmpty()) { Commented [PS9]: @RequestParam used to extract the
throw new NoNameFoundException(); // User Defined exception query parameters form the URL. It is also known as a query
} else { parameter.
m.addAttribute("Emp", emp);
return "index";
}
}

@GetMapping("/add")
public String redirecttoAdd(Model m) {
Employee e = new Employee();
m.addAttribute("emp", e);
return "add";
}

P a g e 4 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

@PostMapping("/save")
public String save(@Valid @ModelAttribute("emp") Employee e, BindingResult result) { Commented [PS10]: @Valid annotation will tell spring
if (result.hasErrors()) { to go and validate the data passed into the controller

return "add"; Commented [PS11]: @ModelAttribute binds a method


} parameter or method return value to a named model
repo.save(e); attribute, and then exposes it to a web view.
return "redirect:/employee"; Commented [PS12]: Interface BindingResult Extends
} the Errors interface for error registration capabilities,
allowing for a Validator to be applied, and adds binding-
// @PostMapping("/save") specific analysis and model building.
// public String save(@ModelAttribute("emp") Employee emp){
//
// repo.save(emp);
// return "redirect:/employee";
// }
@GetMapping("/delete")
public String delete(@RequestParam String id) {
int i = Integer.parseInt(id);
repo.deleteById(i);
return "redirect:/employee";
}

@GetMapping("/update")
public String update(@RequestParam String id, Model m) { Commented [PS13]: @RequestParam is used to
int i = Integer.parseInt(id); capture query parameters or form parameters from the
Employee e = repo.findById(i).get(); URL, whereas @PathVariable is used to capture values
m.addAttribute("emp", e); from the URL path
return "update";
}

@GetMapping("/{id}")
public String updateEmp(@PathVariable int id, Model m) { Commented [PS14]: @PathVariable annotation is
Employee e = repo.findById(id).get(); used to extract the value from the URI.
m.addAttribute("Emp", e);
return "index";
}

P a g e 5 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

@PostMapping("/updateEmp")
public String updateEmp(@RequestParam String id, @RequestParam String name, @RequestParam String mob,
@RequestParam String salary) {
Employee e = new Employee();
e.setId(Integer.parseInt(id));
e.setName(name);
e.setMob(Long.parseLong(mob));
e.setSalary(Double.parseDouble(salary));
repo.save(e);
return "redirect:/employee"; Commented [PS15]: redirect: prefix Spring provides
} another option to perform redirection,

P a g e 6 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

4) Controller Class 2 for postman


@RestController
@RequestMapping("/emp")
public class PostmanController {
@Autowired
EmpRepository repo;

@GetMapping("/{id}")
public ResponseEntity<Employee> getById(@PathVariable Integer id) { Commented [PS16]: ResponseEntity represents the
Optional<Employee> o = repo.findById(id); whole HTTP response: status code, headers, and body.
if (o.isPresent()) { As a result, we can use it to fully configure the HTTP
return ResponseEntity.ok().header("head", "Employee details").body(o.get()); response.
// return new ResponseEntity<>(o.get(),HttpStatus.OK);
} else
return ResponseEntity.status(HttpStatus.NOT_FOUND).header("head", "No Employee").build();
}

@GetMapping("/name")
public String headerData(@RequestHeader String name) { Commented [PS17]: @RequestHeader annotation used to
System.out.println(name); bind a request header to a method argument in a controller.
return name;
}

@GetMapping
public String createSession(HttpSession session) { // create session
session.setAttribute("emp", "mohan");
return "mohan is added to session";
}

@GetMapping("find/{name}")
public String findNo(@PathVariable String name) {
long mob = repo.noByName(name); Commented [PS18]: Custom method created in
repository
return name + ": " + mob;
}

P a g e 7 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

@GetMapping("/session")
public String getSession(@SessionAttribute String emp) { // get session attribute Commented [PS19]: @SessionAttributes is used to bind
session attributes or values in the HTTP Servlet session to a
return emp; controller method parameter
}
}

P a g e 8 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

5) Rest Controller Advice's


@RestControllerAdvice Commented [PS20]: Rest Controller Advice's methods
public class ExceptionHandlingClass { (annotated with @ExceptionHandler ) are shared
@ResponseStatus(HttpStatus.NOT_FOUND) globally across multiple @Controller components to
@ExceptionHandler(NoSuchElementException.class) capture exceptions and translate them to HTTP
public String noEmployee(NoSuchElementException ex) { responses.
return ex.getMessage();
}

@ResponseStatus(HttpStatus.BAD_REQUEST) Commented [PS21]: @ResponseStatus marks a


@ExceptionHandler(NoNameFoundException.class) method or exception class with the status code and
public Map<String, String> noEmployee(NoNameFoundException ex) { reason message that should be returned.
Map<String, String> map = new HashMap<>();
map.put("status", HttpStatus.BAD_REQUEST.toString());
map.put("error", ex.getMessage());
return map;
}

@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NullPointerException.class) Commented [PS22]: @ExceptionHandler is an
public Map<String, String> noEmployee(NullPointerException ex) { annotation used to handle the specific exceptions and
Map<String, String> map = new HashMap<>(); sending the custom responses to the client.
map.put("status", HttpStatus.NOT_FOUND.toString());
map.put("error", ex.getMessage());
return map;
}
}

P a g e 9 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

6) User defined Runtime Exception


public class NoNameFoundException extends RuntimeException { Commented [PS23]: User Defined exception class

public NoNameFoundException() {
super("Employee not exist");
}
}

P a g e 10 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

7) Main class

@SpringBootApplication Commented [PS24]: @SpringBootApplication is


public class WebApp5Application { equivalent to using @Configuration,
@EnableAutoConfiguration and @ComponentScan with
public static void main(String[] args) { their default values.If you are starting your project, it’s
ConfigurableApplicationContext ctx= SpringApplication.run(WebApp5Application.class, args); recommended to use annotation.
EmpRepository repo=ctx.getBean(EmpRepository.class);

System.out.println("done");
}

P a g e 11 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

8) Home page to view all employee details


<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org"> Commented [PS25]: The Thymeleaf is an open-source


<head> Java library that is licensed under the Apache License 2.0.
<meta charset="ISO-8859-1">
It is a HTML5/XHTML/XML template engine. It is
<!-- Latest compiled and minified CSS -->
a server-side Java template engine for both web (servlet-
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
based) and non-web (offline) environments. It is perfect for
modern-day HTML5 JVM web development. It provides full
<title>Employee</title>
integration with Spring Framework.
</head>
<body>
<div class="container">

<h1 class="text-center">Employee Details</h1>


<div class="row">
<div class="col">
<h2><a href="/employee">Home</a></h2>
</div>
<div class="col">
<form action="search" method="post">
<label for="name">name</label>
<input type="text" name="name">
<button type="submit" class="btn btn-primary">search</button>
</form>
</div>
</div>
<table class="table text-center">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Mob</th>
<th scope="col">Salary</th>
<th scope="col" >Action</th>
</tr>
</thead>

P a g e 12 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

<tbody>
<tr th:each="myEmp : ${Emp}"> Commented [PS26]: Th:each is an attribute used to
<td th:text="${myEmp.id}"></td> iterate over collections (lists, sets, arrays, etc.)
<td th:text="${myEmp.name}"></td>
<td th:text="${myEmp.mob}"></td> Commented [PS27]: ${Emp} where Emp is a collection
<td th:text="${myEmp.salary}"></td> object
<td> Commented [PS28]: variable expressions (${...}) The
<a class="btn btn-primary" th:href="@{employee/update(id=${myEmp.id})}" role="button">Update</a>
expression inside the curly braces represents the name
<a class="btn btn-danger" th:href="@{employee/delete(id=${myEmp.id})}" role="button">Delete</a>
of the variable in the model.
</td>
Commented [PS29]: Th:text attribute will replace the
</tr> inner text of the HTML element with the value of the
</tbody> expression.
</table>
Commented [PS30]: Th:href It allows you to create
<div class="text-center">
hyperlinks (anchors) with dynamic URLs based on values
<a class="btn btn-success" href="employee/add" role="button" style="width: 200px;">Add</a>
from your model or Thymeleaf context.
</div>
</div>
</body>
</html>

• ${...} - Variable Expressions. These are the standard expressions.


• *{...} - Selection Variable Expressions. These are the same as variable expressions, except that they are used in combination with a a th:object
attribute. For example, if you have <form th:object="${form}">, then the expression *{field} resolves to ${form.field}. These are mostly used when
using th:field attributes while creating a form.
• #{...} - Message Expressions. These expressions are mainly used to externalize text. For example, to provide text in different languages by reading
from a messages file.
• @{...} - Link URL Expressions. Used to generate URLs.
• ~{...} - Fragment Expression. Used to specify which fragment to include.

P a g e 13 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

9) Page for Add Employee details


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<title>Add Employee</title>
</head>
<body>
<div class="container mt-5" >
<form th:action="@{/employee/save}" method="post" th:object="${emp}"> Commented [PS31]: Th:action is a useful attribute for
<label for="name">name</label> creating dynamic form submissions, allowing you to send
<input type="text" th:field="*{name}"> form data to different URLs based on the context or user
<h3 th:each="er : ${#fields.errors('name')}" th:text="${er}"></h3> input.

<label for="name" >mob</label> Commented [PS32]: th:field is used with *{name} to bind
<input type="text" th:field="*{mob}"> a form field to a name property in the model.
<h3 th:each="er : ${#fields.errors('mob')}" th:text="${er}"></h3> Commented [PS33]: #fields object is used to access form-
related information, including form field errors, during form
<label for="name">salary</label> processing and validation.
<input type="text" th:field="*{salary}">
<h3 th:each="er : ${#fields.errors('salary')}" th:text="${er}"></h3> Commented [PS34]: When a form is submitted and
<button type="submit" class="btn btn-primary">save</button> validation fails on the server side, the controller or service
</form> handling the form submission can add validation errors to
</div> the BindingResult object. Thymeleaf, in turn, provides an
</body> easy way to access these errors through the #fields object in
</html> the template.
#fields.errors handle form field errors and display error
• ${emp} is a model attribute (typically passed to the template from the controller) that contains an object representing an employee with a salary property. messages.
• th:object="${emp}" sets the context object for the form, so all form fields within the form will be bound to properties of the employee object.
• th:field="*{salary}" is used to bind the <input> field to the salary property of the employee object. Thymeleaf will automatically generate the appropriate
name, id, and value attributes for the input field based on the property name.

P a g e 14 | 15
PRAGYANAND SINGH
CRUD OPERATION WITH SPRING BOOT

10) Page for update Employee’s details


</head>
<body>
<div class="container">
<h3>EmpId= <span th:text="${emp.id}" > </span></h3>
<form action="updateEmp" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="id" placeholder="Enter name" name="id" th:value="${emp.id}"> Commented [PS35]: th:value="${emp.id}": This sets the
</div> value of the <input> field to the value of the id property of
<div class="form-group"> the emp object in the Thymeleaf context (usually from the
<label for="name">name</label> model).
<input type="text" class="form-control" id="name" placeholder="Enter name" name="name" th:value="${emp.name}">
</div>
<div class="form-group">
<label for="name">mob</label>
<input type="text" class="form-control" id="mob" placeholder="Enter name" name="mob" th:value="${emp.mob}">
</div>
<div class="form-group">
<label for="name">salary</label>
<input type="text" class="form-control" id="salary" placeholder="Enter name" name="salary"
th:value="${emp.salary}">
</div>
<button type="submit" class="btn btn-primary">save</button>
</form>
</div>
</body>
</html>

P a g e 15 | 15

You might also like