Spring Boot Backend Development Course, Blog Screen Layout Example, Adding Creation and Modification Time to the Entity

Blog Screen Composition Example

Developing a blog web application using Spring Boot is a very useful skill in modern web development. In this tutorial, we will cover how to create a simple blog screen using Spring Boot and also learn how to add creation and modification timestamps to the entity.

1. What is Spring Boot?

Spring Boot is an open-source framework that helps you use the Java-based Spring framework more easily. Its main feature is minimizing initial setup and configuration so that developers can focus on business logic. In this tutorial, we will implement various features while creating a blog application using Spring Boot.

2. Project Setup

To set up a Spring Boot project, we use Spring Initializr. You can create a project with the following settings.

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 2.5.x or the latest version
  • Group: com.example
  • Artifact: blog
  • Dependencies: Spring Web, Spring Data JPA, H2 Database, Lombok

Open the created project in your IDE and start working.

3. Blog Entity Structure

The core of the blog application is the Post entity. This entity represents a blog post and usually includes a title, content, creation time, and modification time.

package com.example.blog.entity;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.time.LocalDateTime;

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

    private String title;

    @Column(length = 10000)
    private String content;

    private LocalDateTime createdAt;

    private LocalDateTime updatedAt;

    @PrePersist
    public void onCreate() {
        this.createdAt = LocalDateTime.now();
    }

    @PreUpdate
    public void onUpdate() {
        this.updatedAt = LocalDateTime.now();
    }
}

The code above shows the structure of the Post entity. The @Entity annotation indicates that this class is a JPA entity, and @Id and @GeneratedValue are used to generate the primary key. Creation and modification times are automatically managed using LocalDateTime.

4. Database Configuration

In this example, we will use the H2 database. Add the following to the application.properties file to configure the H2 database.

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create

Enabling the H2 console allows you to directly access the database through a browser.

5. Create Repository Interface

We create a repository for interactions with the database. By using Spring Data JPA, basic CRUD functionality is provided just by defining the interface.

package com.example.blog.repository;

import com.example.blog.entity.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository {
}

6. Implement Service Layer

The service layer is where business logic is handled. We will create a PostService class to implement CRUD functionality for blog posts.

package com.example.blog.service;

import com.example.blog.entity.Post;
import com.example.blog.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PostService {

    @Autowired
    private PostRepository postRepository;

    public List findAll() {
        return postRepository.findAll();
    }

    public Post findById(Long id) {
        return postRepository.findById(id).orElse(null);
    }

    public Post save(Post post) {
        return postRepository.save(post);
    }

    public void delete(Long id) {
        postRepository.deleteById(id);
    }
}

7. Implement Controller

Now we will create a PostController to handle user requests. This controller defines REST APIs and manages interactions with clients.

package com.example.blog.controller;

import com.example.blog.entity.Post;
import com.example.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Autowired
    private PostService postService;

    @GetMapping
    public List getAllPosts() {
        return postService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity getPostById(@PathVariable Long id) {
        Post post = postService.findById(id);
        return post != null ? ResponseEntity.ok(post) : ResponseEntity.notFound().build();
    }

    @PostMapping
    public Post createPost(@RequestBody Post post) {
        return postService.save(post);
    }

    @PutMapping("/{id}")
    public ResponseEntity updatePost(@PathVariable Long id, @RequestBody Post post) {
        post.setId(id);
        Post updatedPost = postService.save(post);
        return ResponseEntity.ok(updatedPost);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deletePost(@PathVariable Long id) {
        postService.delete(id);
        return ResponseEntity.noContent().build();
    }
}

8. Run Spring Boot Application

Once all configurations are completed, you can run the application by executing the BlogApplication class.

package com.example.blog;

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

@SpringBootApplication
public class BlogApplication {

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

9. Summary of Overall Flow

All of the above processes are steps to implement a RESTful API for creating, modifying, and deleting posts. The frontend can be designed using modern frameworks like React or Vue.js, while the backend interacts with data through the above APIs.

10. Other Considerations

When developing a blog application, various features need to be considered. For example, user authentication and authorization, comment functionality, and a tagging system. These features can be implemented through additional entities and service classes.

In Conclusion

Developing a blog application using Spring Boot will be a very rewarding experience. It will enhance your understanding of the Spring framework, JPA, and RESTful APIs. I hope you can expand and develop your projects based on what we covered in this tutorial.

Appendix: References