Start Creating User API

User.java

User.java Structure

  1. MySql Database - Name (cx_blog_db)

  2. Folder Structure

 src
  └── main
       └── java
             └── com.manage.backend.codexam
                                         └── entities
                                               └── User.java
User.java
package com.manage.backend.codexam.entities;
 
        import jakarta.persistence.*;
        import lombok.Getter;
        import lombok.NoArgsConstructor;
        import lombok.Setter;
 
        @Entity
        @Table(name = "users")
        @NoArgsConstructor
        @Getter
        @Setter
        public class User {
 
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
 
        private int id;
 
        @Column(name = "user_name", nullable = false , length = 100)
        private String name;
        private String email;
        private String password;
        private String about;
 
 
    }
  1. Run the "BackendAppIication.java" file to start the server then open MySql Workbench and create a database named cx_blog_db and refresh the schemas in the database you can see Table named users and select the user right click to Select Rows and you can see the data in the table.
        SELECT * FROM cx_blog_db.users;

You can see id , about , email , user_name , password in the table.

⚡️
  1. package: This keyword is used to declare the package that the class belongs to. In this case, the class User is part of the package com.manage.backend.codexam.entities. Packages are used to organize Java classes into different namespaces, which can help prevent naming conflicts and make it easier to locate a specific class.

  2. import: This keyword is used to import other Java classes that are needed by the current class.

  • jakarta.persistence.* :This package contains a set of classes and interfaces that provide an object/relational mapping facility for Java applications. This means that it allows you to map your Java objects to the tables in a relational database.
  • lombok.Getter: Lombok is a library that can automatically generate getters, setters, constructors, and other boilerplate code for Java classes. Here @Getter is used to generate getter method for every fields in class.
  • lombok.Setter: Here @Setter is used to generate setter method for every fields in class.
  • lombok.NoArgsConstructor: This is used for generate no-args constructor for the class.
  1. @Entity: This is a JPA (Java Persistence API) annotation that marks the User class as an entity, which means that it can be persisted to a relational database using JPA.

  2. @Table(name = "users"): This is another JPA annotation that maps the User class to a specific table in the database. The name attribute specifies the name of the table, which in this case is "users".

  3. @NoArgsConstructor: This annotation is from lombok library which tells the compiler to generate a constructor with no arguments.

  4. @Getter: This annotation is also from lombok, it tells the compiler to generate getter method for every fields in class.

  5. @Setter: This annotation is also from lombok, it tells the compiler to generate setter method for every fields in class.

  6. class: This keyword is used to declare a new class in Java. In this case, the class is called User.

  7. @Id: This is a JPA annotation that marks the id field as the primary key for the User entity.

  8. @GeneratedValue(strategy = GenerationType.AUTO) : This JPA annotation is used to specify that the primary key id should be generated automatically by the database when a new User entity is persisted. It uses GenerationType.AUTO as strategy to generate the primary key.

  9. private int id;: This line declares a private integer field called id which is marked as primary key by @Id.

  10. @Column(name = "user_name", nullable = false , length = 100) : This JPA annotation is used to specify additional properties of the name field when it is mapped to a column in the "users" table. The name attribute specifies the name of the column in the table, which in this case is "user_name". The nullable attribute specifies whether the column can contain a null value, which in this case is false. The length attribute specifies the maximum length of the column in the table. In this case, it is set to 100, meaning that the "user_name" column can contain a maximum of 100 characters. The @Column annotation is used to customize the default column and table name mapping that JPA generates automatically when mapping entities to database tables.

  • private String name; : This line declares a private String field called name which is marked as a column in the table "users" by @Column annotation with name "user_name", can not be null and has maximum length of 100.

  • private String email;: This line declares a private String field called email which is marked as a column in the table "users" and has not been specified any column level properties.

  • private String password;: This line declares a private String field called password which is marked as a column in the table "users" and has not been specified any column level properties.

  • private String about;: This line declares a private String field called about which is marked as a column in the table "users" and has not been specified any column level properties.

In summary, this Java class User represents an entity with name User which is to be persisted to relational databases via JPA. The class has 4 fields name, email, password, about and one primary key id and specifies the column properties for some fields via JPA annotations. Getter setter method will be generated automatically using lombok, and no args constructor is also generated using lombok.

UserRepo.java

UserRepo.java Structure

  1. MySql Database - Name (cx_blog_db) -> Drop the user from Tables in cx_blog_db (MySql Workbench)

  2. Folder Structure

src
└── main
      └── java
            └── com.manage.backend.codexam
                                     └── repository
                                            └── UserRepo.java
 
UserRepo.java
package com.manage.backend.codexam.repository;
 
import com.manage.backend.codexam.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
 
public interface UserRepo extends JpaRepository<User,Integer> {
 
}
 
ℹ️

This code defines an interface for a repository that provides CRUD operations for User entities using Spring Data JPA.

ℹ️

JpaRepository is a Spring Data interface for performing CRUD operations on a repository of a specific type. It is part of the Spring Data project, which aims to provide a consistent programming model for data access in Java applications.

JpaRepository is a subinterface of CrudRepository and it's specific for JPA based repositories which provide additional methods for creating, reading, updating and deleting records in the database using the Java Persistence API (JPA). JPA is a specification for object-relational mapping in Java, which allows for managing relational data in Java applications using a common API.

The main goal of Spring Data JPA is to make it easy to build Spring-powered applications that use JPA to store data in a relational database. By extending the JpaRepository interface and providing it with the type of the entity and the type of the primary key, you can easily create a repository that can perform basic CRUD operations on the entity, like saving and retrieving records, without the need to write any implementation code.

It also simplify the implementation of data access layers by reducing the amount of boilerplate code required and providing a consistent programming model across different data access technologies.

JpaRepository has many inbuilt method which can use as is, or you can also define your custom methods using it.

UserService.java

UserService.java Structure

src
└── main
        └── java
                └── com.manage.backend.codexam
                                         └── services
                                                └── UserService.java
UserService.java
package com.manage.backend.codexam.services;
 
import com.manage.backend.codexam.entities.User;
import com.manage.backend.codexam.payloads.UserDto;
 
import java.util.List;
 
public interface UserService {
UserDto createUser(UserDto user);
UserDto updateUser(UserDto user , Integer userid);
UserDto getUserById(Integer userid);
 
List<UserDto> getAllUsers();
 
void deleteUser(Integer userid);
 
}
ℹ️

This interface does not provide an implementation of the methods, it's just describing the methods that need to be implemented in classes that implement this interface. The class implementing this interface will provide the behavior of these methods and can be used to perform user related tasks like adding, updating, or deleting users, or retrieving user information. It will have the implementation of these methods which actually performs the operation.

createUser takes in an object of UserDto and returns the created object. updateUser takes in an object of UserDto and an integer userid, it update the user information and returns the updated user object getUserById takes in an integer userid and returns the user object for that id. getAllUsers returns a list of all user objects. deleteUser takes in an integer userid and deletes the user associated with that id.

💥

To install lombok in IntelliJ IDEA - Simple Install The Plugins

Or Other Ide like STS - First download the lombok file from the official website and paste it inside the folder of your IDE and then open terminal and type this

java -jar lombok.jar

Then follow the steps and install it.

  • A installer window will open just specify the location of your IDE(select Spring Tool Suite.exe) and click on install.
  • After installation is complete restart your IDE.
  • Now you can use lombok in your project.

UserDto.java

UserDto.java Structure

src
└── main
        └── java
                └── com.manage.backend.codexam
                                         └── payloads
                                                └── UserDto.java
UserDto.java
package com.manage.backend.codexam.payloads;
 
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
 
@NoArgsConstructor
@Getter
@Setter
 
public class UserDto {
 
private int id;
private String name;
private String email;
 
private String password;
 
private String about;
}
ℹ️

An annotation(@) is a way to add metadata to a Java class, method, or variable. Annotations provide a way to mark a class, method or variable with additional information that can be later used by a tool, framework or library.

@NoArgsConstructor, @Getter, and @Setter are annotations provided by the library "lombok".

@NoArgsConstructor generates a constructor with no arguments. This constructor is useful when you want to create an instance of the class, but you don't have all the required information yet.

@Getter generates a getter method for each field in the class, it allow to access the field from outside the class.

@Setter generates a setter method for each field in the class, it allow to change the field from outside the class.

By using these annotations we don't need to write boiler plate code for constructors and getters/setters, Lombok does that for us.

These annotations are not built-in Java features and they require you to have Lombok library added as a dependency in your project.

In summary, @NoArgsConstructor, @Getter, and @Setter are annotations that are used to generate constructors, getters and setters, respectively, for a class's fields. They are provided by the library Lombok and they allow you to avoid writing boilerplate code for these common operations.