CRUD Operations


In programming,
CRUD operations represent the basic actions you can perform on data in an application or database. CRUD stands for Create, Read, Update, and Delete.

HTML Form for CRUD Operations

<!--Create Operation: Adding a new programmer-->
<form action="addProgrammer" method="post">
<!-- <h3>Enter Programmer's ID</h3>
<input type="text" name="pId" /> -->
<h3>Enter Programmer's Name</h3>
<input type="text" name="pName" />
<h3>Enter Programmer's Language</h3>
<input type="text" name="pLang" />
<button type="submit">Add Programmer</button>
</form>


<!-- Read Operation: Finding a programmer by ID --> <form action="findById" method="get"> <h3>Enter Programmer's ID</h3> <input type="text" name="pId" /> <button type="submit">Find by ID</button> </form> <!-- Read Operation: Finding programmers by name --> <form action="findByName" method="get"> <h3>Enter Programmer's Name</h3> <input type="text" name="pName" /> <button type="submit">Find by Name</button> </form> <!-- Delete Operation: Deleting a programmer by ID --> <form action="deleteById" method="post"> <h3>Enter Programmer's ID</h3> <input type="text" name="pId" /> <button type="submit">Delete</button> </form> <!-- Update Operation: Updating a programmer's information by ID --> <form action="updateById" method="post"> <h3>Enter Programmer's ID</h3> <input type="text" name="pId" /> <h3>Enter Programmer's Name</h3> <input type="text" name="pName" /> <h3>Enter Programmer's Language</h3> <input type="text" name="pLang" /> <button type="submit">Update</button> </form>


Here’s the controller page for performing CRUD operations

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; @Controller public class ProgrammerController { @Autowired private ProgrammerRepository pr; // Create Operation: Adding a new programmer @PostMapping("/addProgrammer") public String addProgrammer(@ModelAttribute Programmer programmer) { pr.save(programmer); // Saves the new programmer in the database return "redirect:/home"; // Redirects to home after adding } // Read Operation: Finding a programmer by ID @GetMapping("/findById") public String findById(@RequestParam int pId, Model m) { // Finding the programmer by ID, or returns null if not found Programmer p = pr.findById(pId).orElse(null); m.addAttribute("programmer", p); // Adds the programmer to the model for display return "ProgrammerInfo.html"; // Page displaying the programmer's info } // Read Operation: Finding programmers by name @GetMapping("/findByName") public String findByName(@RequestParam String pName, Model m) { // Custom repository method to find a list of programmers by name List<Programmer> p = pr.findBypName(pName); m.addAttribute("programmers", p); // Adds the list to the model for display return "AllProgrammersInfo.html"; // Page displaying all programmers with the name } // Update Operation: Updating a programmer's information by ID @PostMapping("/updateById") public String updateById(@ModelAttribute Programmer programmer) { // Finds the programmer by ID; if not found, throws an exception Programmer p = pr.findById(programmer.getpId()).orElseThrow(() -> new RuntimeException("Programmer not found")); // Updates name and language fields p.setpName(programmer.getpName()); p.setpLang(programmer.getpLang()); pr.save(p); // Saves the updated programmer in the database return "ProgrammerInfo.html"; // Page displaying the updated programmer's info } // Delete Operation: Deleting a programmer by ID @PostMapping("/deleteById") public String deleteById(@RequestParam int pId) { pr.deleteById(pId); // Deletes the programmer by ID return "redirect:/home"; // Redirects to home after deletion } }

Query DSL (Domain Specific Language)

Read (findById and findByName):

findById: Uses findById method (built-in) to search by ID and returns a single programmer.
findByName: Uses findBypName (custom repository method) to search for all programmers with
a specified name.

This type of method, like findBypName, is known as a Query DSL (Domain Specific Language)
in Spring Data JPA. In Spring Data, the Query DSL allows you to define custom queries by
simply naming repository methods in a specific pattern, without writing actual SQL or JPQL
code. For example:
findBypName is a method derived from the Query DSL pattern, where Spring Data JPA interprets
the method nameand automatically generates the query to find programmers by the pName field.

@Repository

public interface ProgrammerRepo extends JpaRepository<Programmer, Integer> {


List<Programmer> findBypName(String pName);


}


In Spring Data JPA, Query DSL method names follow specific rules that help you create queries based
on your entity’s fields. Rules for naming methods in repositories:

1. Start with Keywords

  • Query methods in Spring Data often begin with keywords like findBy, getBy, or countBy.
  • For example, findBy tells Spring Data JPA that this method will search for specific data.

2. Use Entity Field Names

  • After the keyword (findBy, getBy), use the name of the entity field you want to search by.
  • This must match exactly with the field name in your entity class.
  • If your entity class has a field pName, you can name the method findBypName to search by that field.
  • For multiple conditions, you can chain fields together with logical keywords like And or Or.

3. Combine Fields with And or Or

  • Use And or Or between fields if you want to add multiple conditions.
  • For example:
    • findBypNameAndpLang: Finds programmers with a specific name and language.
    • findBypNameOrpLang: Finds programmers with a specific name or language.

4. Use Comparators for Conditions

  • You can use specific comparators for different types of conditions:
    • Is or Equals: Checks for exact matches (e.g., findBypNameIs or findBypNameEquals).
    • LessThan / GreaterThan: For numeric or date fields (e.g., findByAgeLessThan).
    • Like: For partial matches or patterns (e.g., findBypNameLike).
    • Between: For a range of values (e.g., findByAgeBetween).
    • IsNull / IsNotNull: Checks for null or non-null values (e.g., findBypLangIsNull).

5. Sort Results with OrderBy

  • Add OrderBy followed by the field name and sort direction (Asc for ascending, Desc for descending).
Example: findBypNameOrderBypLangAsc will find all programmers with a specific name and sort them by
language in ascending order.

Example Summary

Here’s a sample list of method names and what they would do:

  • findBypName: Finds programmers by name.
  • findBypNameAndpLang: Finds programmers by both name and language.
  • findByAgeLessThan: Finds programmers younger than a specific age.
  • findBypLangIsNotNull: Finds programmers whose language field is not empty.
  • findBypNameOrderBypLangDesc: Finds programmers by name and sorts them by language in descending order.

If we want to create a custom query to find programmers by name but wish to use a more meaningful

method name rather than following the standard naming convention, we can use the @Query annotation

in Spring Data JPA. Click here to see how it would look:


Comments