Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Spring boot annotation used in entity class

Class based Annotation:

  • @Entity – used to indicates the class is below to JPA entites.
  • @Table – is used to indicates the table name.
  • @MappedSuperClass – is used to parent entity, which can be inherited by many entities, but it won’t be mapped to its own table. we cannot use @Entity annotation on this class.
@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Getters and setters
    public Long getId() {
        return id;
    }

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

@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {

    private String firstName;
    private String lastName;
    
    // Constructors, getters, setters, other fields...
}
  1. In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
  2. The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
  3. By using @MappedSuperclass, you’re able to create a common base class for your entity hierarchy while allowing each subclass to include additional fields and annotations specific to their needs.
  4. This promotes code reusability and maintains a clean and structured entity hierarchy.

Primary Keys

  • Define a primary key using @Id.
  • Use @GeneratedValue with appropriate strategy for generating primary key values (e.g., GenerationType.IDENTITY, GenerationType.SEQUENCE)
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // other fields, getters, setters
}

Associations

It says the relationship between two entity class.

  1. Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
  2. Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
  3. Utilize mappedBy to define the owning side of bidirectional relationships.
@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "department",cascade=CascadeType.ALL)
    private List<Employee> employees;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // Constructors, getters, setters, other fields...
}

Cascading Operations

  • Use cascade attribute to specify cascading operations (e.g., CascadeType.ALL, CascadeType.PERSIST).
  • Be cautious with cascading DELETE to avoid unintentional data loss.
import javax.persistence.*;
import java.util.List;

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    // Constructors, getters, setters, other fields...
}
  1. CascadeType.ALL: This option specifies that all operations (e.g., persist, merge, remove) should be cascaded from the parent entity (Author) to the child entity (Book).
  2. orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book entity should also be removed from the database

When you perform a cascading operation on the Author entity, the corresponding operation will cascade to the associated Book entities. For instance.

Author author = new Author();
author.setName("J.K. Rowling");

Book book1 = new Book();
book1.setTitle("Harry Potter and the Sorcerer's Stone");
book1.setAuthor(author);

Book book2 = new Book();
book2.setTitle("Harry Potter and the Chamber of Secrets");
book2.setAuthor(author);

author.setBooks(Arrays.asList(book1, book2));

// Cascading persist: Saving the author will also save both associated books.
entityManager.persist(author);

Likewise, cascading operations work for merge, remove, and other entity operations, reducing the need for explicitly managing related entities persistence.

Validation

Use validation annotations (@NotNull, @Size, etc.) to enforce data integrity constraints directly in the entity class.
Combine JPA validation with Spring’s @Valid annotation to automatically validate incoming data.

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Title is required")
    @Size(max = 100, message = "Title must be at most 100 characters")
    private String title;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
    private List<Comment> comments;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Text is required")
    @Size(max = 500, message = "Text must be at most 500 characters")
    private String text;

    @ManyToOne
    @JoinColumn(name = "post_id")
    private Post post;

    // Constructors, getters, setters, other fields...
}

Auditing

  • Implement entity auditing by adding fields like @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate for tracking who created or modified an entity and when.
  • Utilize Spring’s @EntityListeners to manage the auditing behavior.
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class Auditable {
    @CreatedBy
    protected String createdBy;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    protected LocalDateTime createdDate;

    @LastModifiedBy
    protected String lastModifiedBy;

    @LastModifiedDate
    protected LocalDateTime lastModifiedDate;

    // Getters and setters...
}
  1. @EntityListeners(AuditingEntityListener.class): This annotation specifies that this entity should be audited using the provided entity listener class. Spring Data JPA will automatically update the auditing fields before persisting or updating the entity.
  2. @MappedSuperclass: This annotation indicates that this class is not an entity itself but serves as a base class for other entities. It allows attributes and behaviors to be inherited by other entities.
  3. @CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
  4. @CreatedDate: This annotation marks the field to store the timestamp when the entity was created. The nullable and updatable properties are set to false to ensure that this field is populated during creation and not updated afterwards.
  5. @LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
  6. @LastModifiedDate: This annotation marks the field to store the timestamp when the entity was last modified.

By implementing auditing, you can track who created or modified entities and when those actions occurred. This information can be invaluable for monitoring and maintaining your application’s data.

Enums and Enumerated Types

  • Use Java enums for fields with predefined values.
  • Annotate enum fields with @Enumerated(EnumType.STRING) to store enum values as strings in the database.
@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    private TaskStatus status;
    // other fields, getters, setters
}

public enum TaskStatus {
    TODO, IN_PROGRESS, DONE
}

Reference:

Spring boot annotation used in entity class

17 April 2025 at 16:54

Class based Annotation:

  • @Entity – used to indicates the class is below to JPA entites.
  • @Table – is used to indicates the table name.
  • @MappedSuperClass – is used to parent entity, which can be inherited by many entities, but it won’t be mapped to its own table. we cannot use @Entity annotation on this class.
@MappedSuperclass
public abstract class BaseEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Getters and setters
    public Long getId() {
        return id;
    }

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

@Entity
@Table(name = "employees")
public class Employee extends BaseEntity {

    private String firstName;
    private String lastName;
    
    // Constructors, getters, setters, other fields...
}
  1. In this example, the BaseEntity class is annotated with @MappedSuperclass. It contains the common fields that you want to share across multiple entity classes.
  2. The Employee class inherits from BaseEntity, effectively inheriting the id field from the superclass.
  3. By using @MappedSuperclass, you’re able to create a common base class for your entity hierarchy while allowing each subclass to include additional fields and annotations specific to their needs.
  4. This promotes code reusability and maintains a clean and structured entity hierarchy.

Primary Keys

  • Define a primary key using @Id.
  • Use @GeneratedValue with appropriate strategy for generating primary key values (e.g., GenerationType.IDENTITY, GenerationType.SEQUENCE)
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // other fields, getters, setters
}

Associations

It says the relationship between two entity class.

  1. Use @OneToOne, @OneToMany, @ManyToOne, and @ManyToMany to define relationships between entities.
  2. Use fetch attribute to control loading behavior (e.g., LAZY or EAGER).
  3. Utilize mappedBy to define the owning side of bidirectional relationships.
@Entity
public class Department {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "department",cascade=CascadeType.ALL)
    private List<Employee> employees;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

    // Constructors, getters, setters, other fields...
}

Cascading Operations

  • Use cascade attribute to specify cascading operations (e.g., CascadeType.ALL, CascadeType.PERSIST).
  • Be cautious with cascading DELETE to avoid unintentional data loss.
import javax.persistence.*;
import java.util.List;

@Entity
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Book> books;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;

    @ManyToOne
    @JoinColumn(name = "author_id")
    private Author author;

    // Constructors, getters, setters, other fields...
}
  1. CascadeType.ALL: This option specifies that all operations (e.g., persist, merge, remove) should be cascaded from the parent entity (Author) to the child entity (Book).
  2. orphanRemoval = true: This option specifies that when an Author entity’s reference to a Book entity is removed from the books collection, the orphaned Book entity should also be removed from the database

When you perform a cascading operation on the Author entity, the corresponding operation will cascade to the associated Book entities. For instance.

Author author = new Author();
author.setName("J.K. Rowling");

Book book1 = new Book();
book1.setTitle("Harry Potter and the Sorcerer's Stone");
book1.setAuthor(author);

Book book2 = new Book();
book2.setTitle("Harry Potter and the Chamber of Secrets");
book2.setAuthor(author);

author.setBooks(Arrays.asList(book1, book2));

// Cascading persist: Saving the author will also save both associated books.
entityManager.persist(author);

Likewise, cascading operations work for merge, remove, and other entity operations, reducing the need for explicitly managing related entities persistence.

Validation

Use validation annotations (@NotNull, @Size, etc.) to enforce data integrity constraints directly in the entity class.
Combine JPA validation with Spring’s @Valid annotation to automatically validate incoming data.

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Title is required")
    @Size(max = 100, message = "Title must be at most 100 characters")
    private String title;

    @OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
    private List<Comment> comments;

    // Constructors, getters, setters, other fields...
}

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Text is required")
    @Size(max = 500, message = "Text must be at most 500 characters")
    private String text;

    @ManyToOne
    @JoinColumn(name = "post_id")
    private Post post;

    // Constructors, getters, setters, other fields...
}

Auditing

  • Implement entity auditing by adding fields like @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate for tracking who created or modified an entity and when.
  • Utilize Spring’s @EntityListeners to manage the auditing behavior.
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class Auditable {
    @CreatedBy
    protected String createdBy;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    protected LocalDateTime createdDate;

    @LastModifiedBy
    protected String lastModifiedBy;

    @LastModifiedDate
    protected LocalDateTime lastModifiedDate;

    // Getters and setters...
}
  1. @EntityListeners(AuditingEntityListener.class): This annotation specifies that this entity should be audited using the provided entity listener class. Spring Data JPA will automatically update the auditing fields before persisting or updating the entity.
  2. @MappedSuperclass: This annotation indicates that this class is not an entity itself but serves as a base class for other entities. It allows attributes and behaviors to be inherited by other entities.
  3. @CreatedBy: This annotation specifies the field to store the username of the user who created the entity.
  4. @CreatedDate: This annotation marks the field to store the timestamp when the entity was created. The nullable and updatable properties are set to false to ensure that this field is populated during creation and not updated afterwards.
  5. @LastModifiedBy: This annotation specifies the field to store the username of the user who last modified the entity.
  6. @LastModifiedDate: This annotation marks the field to store the timestamp when the entity was last modified.

By implementing auditing, you can track who created or modified entities and when those actions occurred. This information can be invaluable for monitoring and maintaining your application’s data.

Enums and Enumerated Types

  • Use Java enums for fields with predefined values.
  • Annotate enum fields with @Enumerated(EnumType.STRING) to store enum values as strings in the database.
@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    private TaskStatus status;
    // other fields, getters, setters
}

public enum TaskStatus {
    TODO, IN_PROGRESS, DONE
}

Reference:

Deploy our Spring boot application for free.

14 April 2025 at 18:46

In this blog, we are going to deploy out spring boot application with PostgreSQL using to

  • Web site on render.com
  • PostgreSQl on neon.com

Create an Application

We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.

Frontent (Thyme Leaf)

I am going to create html that can integrate with thyme leaf.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
	<title> first page </title>	
</head>
<body>
	<div>
		<h1>Heading name</h1>
		<p><span th:text="${word}"></span></p> 
	</div>	
	
	<div>
			<h1>list</h1>
			<p><span th:text="${word}"></span></p> 
	</div>
</body>
		
</html>

Create a html in spring boot

Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.

Spring boot Controller layer

I create controller class which can map the html with java class.

@Controller
public class ControllerClass {
	
	@GetMapping
	public String getInitialisePage(Model model) {
		String p = "ravana";
		model.addAttribute("word",p);
		return "index";
	}
}

Create a Repository Interface

we are going to do dataBase configuaration and spring JPA here.

Configuration of Database and JPA

Configure the Database and JPA on Application.Properties.

spring.datasource.url =  ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.

Using Eclipse or Spring tool suit IDE

  • Right click on our project.
  • Run as -> run configurations
  • click the environment and set the name and value.
  • Eg. name = DATASOURCE_URL and value = our jbdc url
  • Eg. name = DATASOURCE_USERNAME and value = our username
  • Eg. name = DATASOURCE_PASSWORD and value = our Password

Create jar file from our project

When we create Spring boot project we have .mvn file. Delete the test related dependency and class.

    ./mvnw clean package
If not work copy this below code. This is work on linux only
      export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
      export SPRING_USERNAME="postgres"
      export DATASOURCE_PASSWORD="1234"

      //don't be panic as run again to run ./mvnw clean package
      // else give this command
      // remove the test depandancy and delete src/main/test.
      // ./mvnw clean package

Create a docker file

Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.

     # Use an official Maven image to build the Spring Boot app
     FROM maven:3.8.4-openjdk-17 AS build
    
    # Set the working working directory
    WORKDIR /app
    
    # Copy the pom.xml and install dependencies
    COPY pom.xml .
    RUN mvn dependency:go-offline

    # Copy the source code and build the application
    COPY src ./src
    RUN mvn clean package -DskipTests # This will download the all depandencies
    
    # Use an official OpenJDK image to run the application
    FROM openjdk:17-jdk-slim

    #Set the working directory
    WORKDIR /app

    # Copy the built JAR file from the build stage
    COPY --from=build /app/target/file-name.jar .
      # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
    
    # Expose port 8080
    EXPOSE 8080

    # Specify the command to run the application
    ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
      # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
      # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
 

Create Docker image

After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.

  docker build -t demo_deployment .

  docker tag demo-deployment kalaiarasan23/demo-deployment:latest

  docker push kalaiarasan23/demo-deployment:latest

Host our Database

Go to neon.tech, create account we got free 500MB space DB. Now create project and add.

Important is to get the configutation because we will use in application part.

 postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require

    Select the environmental variable on render.com
    DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
    DATASOURCE_USERNAME=username
    DATASOURCE_PASSWORD=password

Host the Web application

Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.

Reference :

Deploy our Spring boot application for free.

In this blog, we are going to deploy out spring boot application with PostgreSQL using to

  • Web site on render.com
  • PostgreSQl on neon.com

Create an Application

We can create application that can interact with html and controller layer of our application. Then, service layer that can interact with Repository layer.

Frontent (Thyme Leaf)

I am going to create html that can integrate with thyme leaf.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
	<title> first page </title>	
</head>
<body>
	<div>
		<h1>Heading name</h1>
		<p><span th:text="${word}"></span></p> 
	</div>	
	
	<div>
			<h1>list</h1>
			<p><span th:text="${word}"></span></p> 
	</div>
</body>
		
</html>

Create a html in spring boot

Go to template and create our html pages and Go to static from create js and CSS files. I paste above code on the index.html.

Spring boot Controller layer

I create controller class which can map the html with java class.

@Controller
public class ControllerClass {
	
	@GetMapping
	public String getInitialisePage(Model model) {
		String p = "ravana";
		model.addAttribute("word",p);
		return "index";
	}
}

Create a Repository Interface

we are going to do dataBase configuaration and spring JPA here.

Configuration of Database and JPA

Configure the Database and JPA on Application.Properties.

spring.datasource.url =  ${DATASOURCE_URL}
spring.datasource.username= ${DATASOURCE_USERNAME}
spring.datasource.password= ${DATASOURCE_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

spring.jpa.hibernate.ddl-auto = update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform= org.hibernate.dialect.PostgreSQLDialect

Now, the database url, userName, password are assigned as Environment variables. So, now we want to assign as in different approach by IDE.

Using Eclipse or Spring tool suit IDE

  • Right click on our project.
  • Run as -> run configurations
  • click the environment and set the name and value.
  • Eg. name = DATASOURCE_URL and value = our jbdc url
  • Eg. name = DATASOURCE_USERNAME and value = our username
  • Eg. name = DATASOURCE_PASSWORD and value = our Password

Create jar file from our project

When we create Spring boot project we have .mvn file. Delete the test related dependency and class.

    ./mvnw clean package
If not work copy this below code. This is work on linux only
      export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost:5432/login"
      export SPRING_USERNAME="postgres"
      export DATASOURCE_PASSWORD="1234"

      //don't be panic as run again to run ./mvnw clean package
      // else give this command
      // remove the test depandancy and delete src/main/test.
      // ./mvnw clean package

Create a docker file

Download docker and docker desktop on our system. Create a file on our project, named as Dockerfile.

     # Use an official Maven image to build the Spring Boot app
     FROM maven:3.8.4-openjdk-17 AS build
    
    # Set the working working directory
    WORKDIR /app
    
    # Copy the pom.xml and install dependencies
    COPY pom.xml .
    RUN mvn dependency:go-offline

    # Copy the source code and build the application
    COPY src ./src
    RUN mvn clean package -DskipTests # This will download the all depandencies
    
    # Use an official OpenJDK image to run the application
    FROM openjdk:17-jdk-slim

    #Set the working directory
    WORKDIR /app

    # Copy the built JAR file from the build stage
    COPY --from=build /app/target/file-name.jar .
      # my fileName is demo-0.0.1-SNAPSHOT so COPY --from=build /app/target/demo-0.0.1-SNAPSHOT.jar
    
    # Expose port 8080
    EXPOSE 8080

    # Specify the command to run the application
    ENTRYPOINT ["java", "-jar", "/app/notes-0.0.1-SNAPSHOT.jar"]
      # change the notes-0.0.1-SNAPSHOT.jar into fileName demo-0.0.1-SNAPSHOT
      # ENTRYPOINT ["java", "-jar", "/app/demo-0.0.1-SNAPSHOT.jar"]
 

Create Docker image

After create docker file. Then run the below command on terminal. It will generate a docker image. Check the image on your docker or not.

  docker build -t demo_deployment .

  docker tag demo-deployment kalaiarasan23/demo-deployment:latest

  docker push kalaiarasan23/demo-deployment:latest

Host our Database

Go to neon.tech, create account we got free 500MB space DB. Now create project and add.

Important is to get the configutation because we will use in application part.

 postgresql://username:password2@ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require

    Select the environmental variable on render.com
    DATASOURCE_URL=jdbc:postgresql://ep-shiny-butterfly-a1el75x8-pooler.ap-southeast-1.aws.neon.tech/DB?sslmode=require
    DATASOURCE_USERNAME=username
    DATASOURCE_PASSWORD=password

Host the Web application

Go to render.com and open dashboard -> Click new web services ->click image. Enter the environment variable at last. Deploy our web site and verify the server online or not.

Reference :

❌
❌