Building a note application with Spring boot and Ionic Part 1

Getting Started | Building an Application with Spring Boot




Build an application note with Spring boot and Angular use Jpa

Objective:

In this tutorial we will create an application note to do or create your idea by category the note conent a title, create at, update at end content a description, We ere going use Spring boot for banckend and Ionic Angular for Frontend.


Used Skills in this project:

Java, SpringBoot, MicroServices, REST WebServices, JPA, Hibernate, MySQL Database, Maven, Angular, GitHub, SpringBoot Embedded Tomcat Server, STS-Eclipse IDE


Tools to be used

° Use any IDE to develop the Spring and Hibernate project. It may be STS/Eclipse/Netbeans. Here, we are using STS (Spring Tool Suite).

° Mysql for the database.

° Use any IDE to develop the Angular project. It may be Visual Studio Code/Sublime. Here, we are using Visual Studio Code.

° Server: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.


Spring MVC

Spring MVC is the primary web framework built on the Servlet API. It is build on the popular MVC design pattern. MVC (Model-View-Controller) is a software architecture pattern, which separates application into three areas: model, view, and controller. The model represents a Java object carrying data. The view represents the visualization of the data that the model contains. The controller controls the data flow into model object and updates the view when the data changes. It separates the view and model.


Spring Boot Architecture



Spring Boot is a module of the Spring Framework. It is used to create stand-alone, production-grade Spring Based Applications with minimum efforts. It is developed on top of the core Spring Framework.



Introduction mysql to database

MySQL is a database management system that allows you to manage relational databases. It is open source software backed by Oracle. It means you can use MySQL without paying a dime. Also, if you want, you can change its source code to suit your needs. MySQL can run on various platforms UNIX, Linux, Windows, etc. You can install it on a server or even in a desktop. Besides, MySQL is reliable, scalable, and fast.



Introduction to the POM

POM A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project. It contains default values for most projects. Examples for this is the build directory, which is target; the source directory, which is src/main/java; the test source directory, which is src/main/java; and so on. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal.

pom.xml

    
  
  
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0>/modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.1</version> <relativePath/> </parent> <groupId>org.note</groupId> <artifactId>note</artifactId> <version>0.0.1-SNAPSHOT</version> <name>note</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

Properties File

Properties files are used to keep ‘N’ number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application.properties file under the classpath.

The application.properties file is located in the src/main/resources directory. The code for sample application.properties


We need to create database name it bank

src/main/resources/application.properties

    
  
spring.datasource.url=jdbc:mysql://localhost:3306/note?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC spring.datasource.username=root spring.activemq.password= spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect spring.jpa.hibernate.ddl-auto=update server.port=8080 spring.jpa.database=MYSQL

Class Diagram



Modals / Entities

An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes.


We need to create these entities

-> Category

-> Note


Here, we are Category an Entity

Category.java This object content id, name, createAt, updateAt and relational @ManyToOne with Note

src/main/java/com/note/model/Category.java):



package com.note.modal; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.*; import javax.validation.constraints.NotBlank; @Entity @Table(name = "category") public class Category { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotBlank private String name; @Temporal(TemporalType.TIMESTAMP) private Date createAt; @Temporal(TemporalType.TIMESTAMP) private Date updateAt; @OneToMany(mappedBy = "category", cascade = CascadeType.ALL) private List<Note> notes; public Category() { super(); } public Category(String name, Date createAt, Date updateAt, List<Note> notes) { super(); this.name = name; this.createAt = createAt; this.updateAt = updateAt; this.notes = notes; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } public Date getUpdateAt() { return updateAt; } public void setUpdateAt(Date updateAt) { this.updateAt = updateAt; } public List<Note> getNotes() { return notes; } public void setNotes(List<Note> notes) { this.notes = notes; } public void addNote(Note note) { if (getNotes() == null) { this.notes = new ArrayList<>(); } getNotes().add(note); note.setCategory(this); } }

Here, we are creating an Entity

Note.java This object content id, titel, createAt, updateAt and relational @ManyToOne with Category

src/main/java/com/note/model/Note.java):



package com.note.modal; import java.util.Date; import javax.persistence.*; import javax.validation.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity @Table(name = "note") public class Note { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotBlank private String title; @NotBlank @Column(columnDefinition = "TEXT") private String content; @Temporal(TemporalType.TIMESTAMP) private Date createAt; @Temporal(TemporalType.TIMESTAMP) private Date updateAt; @ManyToOne @JsonBackReference(value = "category") private Category category; public Note() { super(); } public Note(String title, String content, Date createAt, Date updateAt, Category category) { super(); this.title = title; this.content = content; this.createAt = createAt; this.updateAt = updateAt; this.category = category; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } public Date getUpdateAt() { return updateAt; } public void setUpdateAt(Date updateAt) { this.updateAt = updateAt; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }

Spring Data JPA Projections

When using Spring Data JPA to implement the persistence layer, the repository typically returns one or more instances of the root class. However, more often than not, we don't need all the properties of the returned objects.


In such cases, it may be desirable to retrieve data as objects of customized types. These types reflect partial views of the root class, containing only properties we care about. This is where projections come in handy.

We need to create these interface dao

-> CategoryDao

-> NoteDao


Here, we are creating an interface

src/main/java/com/note/dao/CategoryDao.java):



package com.note.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.note.modal.Category; public interface CategoryDao extends JpaRepository<Category, Long> { }

Here, we are creating an interface

src/main/java/com/note/dao/NoteDao.java):



package com.note.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.note.modal.Note; public interface NoteDao extends JpaRepository<Note, Long> { }

The services

Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here


We will create one interface in service package:

-> CategoryService

-> NoteService


Here, we are creating an interface

src/main/java/com/note/service/CategoryService.java):



package com.note.service; import java.util.List; import com.note.modal.Category; public interface CategoryService { Category addCategory(Category category); Category editCategory(Category category, long id); void deleteCategory(long id); Category findCategory(long id); List<Category> findCategories(); }

Here, we are creating an interface

src/main/java/com/note/service/NoteService.java):



package com.note.service; import com.note.modal.Note; public interface NoteService { Note addNote(Note note, long id); Note editNote(Note note, long id); void deleteNote(long id); Note findNote(long id); }

The managers classes implementation

An impl class is usually a class that implements the behaviour described by one of these interfaces. While the internal implementation class, With transactions configured, we can now annotation a bean with @Transactional and @Service either at the class or method level. Then conversion Entity to DTO. This is stands for Data Transfer Object and is a simple Plain Old Java Object which contains class properties and getters and settings methods for accessing those properties.


We will create ont class in the impl package

-> CategoryServiceImpl

-> NoteServiceImpl


Here, we are creating a class impl

src/main/java/com/note/impl/CategoryServiceImpl.java):



package com.note.impl; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.note.dao.CategoryDao; import com.note.modal.Category; import com.note.service.CategoryService; @Transactional @Component public class CategoryServiceImpl implements CategoryService { @Autowired private CategoryDao categoryDao; @Override public Category addCategory(Category category) { category.setCreateAt(new Date()); return categoryDao.save(category); } @Override public Category editCategory(Category category, long id) { Category existsCategory = categoryDao.findById(id).orElse(null); existsCategory.setUpdateAt(new Date()); existsCategory.setName(category.getName()); existsCategory.setCreateAt(null); return categoryDao.save(existsCategory); } @Override public void deleteCategory(long id) { categoryDao.deleteById(id); } @Override public Category findCategory(long id) { return categoryDao.findById(id).orElse(null); } @Override public List<Category> findCategories() { List<Category> categories = categoryDao.findAll(); categories = categories.stream().sorted(Comparator.comparing(Category::getName).reversed()) .collect(Collectors.toList()); return categories; } }

Here, we are creating a class

src/main/java/com/note/impl/NoteServiceImpl.java):



package com.note.impl; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.note.dao.CategoryDao; import com.note.dao.NoteDao; import com.note.modal.Category; import com.note.modal.Note; import com.note.service.NoteService; @Transactional @Component public class NoteServiceImpl implements NoteService { @Autowired private NoteDao noteDao; @Autowired private CategoryDao categoryDao; @Override public Note addNote(Note note, long id) { Category category = categoryDao.findById(id).orElse(null); note.setCreateAt(new Date()); category.addNote(note); return noteDao.save(note); } @Override public Note editNote(Note note, long id) { Note existsNote = noteDao.findById(id).orElse(null); existsNote.setUpdateAt(new Date()); existsNote.setTitle(note.getTitle()); existsNote.setContent(note.getContent()); existsNote.setCreateAt(null); return noteDao.save(existsNote); } @Override public void deleteNote(long id) { noteDao.deleteById(id); } @Override public Note findNote(long id) { return noteDao.findById(id).orElse(null); } }

@RestController API

@RestController is a convenience annotation for creating Restful controllers. It is a specialization of @Component and is autodetected through classpath scanning. It adds the @Controller and @ResponseBody annotations. It converts the response to JSON or XML. It does not work with the view technology, so the methods cannot return ModelAndView. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation.


We will create one class in controller package:

-> CategoryController

-> NoteController


Here, we are creating a class

src/main/java/com/note/controller/CategoryController.java):



package com.note.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.note.modal.Category; import com.note.service.CategoryService; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api") public class CategoryController { @Autowired private CategoryService categoryService; @PostMapping("/addCategory") Category addCategory(@RequestBody Category category) { return categoryService.addCategory(category); } @PutMapping("/editCategory/{id}") Category editCategory(@RequestBody Category category, @PathVariable long id) { return categoryService.editCategory(category, id); } @DeleteMapping("/deleteCategory/{id}") void deleteCategory(@PathVariable long id) { categoryService.deleteCategory(id); } @GetMapping("/findCategory/{id}") Category findCategory(@PathVariable long id) { return categoryService.findCategory(id); } @GetMapping("/findCategories") List<Category> findCategories() { return categoryService.findCategories(); } }

Here, we are creating a class

src/main/java/com/note/controller/NoteService.java):



package com.note.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.note.modal.Note; import com.note.service.NoteService; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api") public class NoteController { @Autowired private NoteService noteService; @PostMapping("/addNote/{id}") Note addNote(@RequestBody Note note, @PathVariable long id) { return noteService.addNote(note, id); } @PutMapping("/editNote/{id}") Note editNote(@RequestBody Note note, @PathVariable long id) { return noteService.editNote(note, id); } @DeleteMapping("/deleteNote/{id}") void deleteNote(@PathVariable long id) { noteService.deleteNote(id); } @GetMapping("/findNote/{id}") Note findNote(@PathVariable long id) { return noteService.findNote(id); } }

NoteApplication

@BookStoreApplication and its use in a simple Spring Boot application. We use the @SpringBootApplication annotation in our Application or Main class to enable a host of features, e.g. Java-based Spring configuration, component scanning, and in particular for enabling Spring


src/main/java/com/note/NoteApplication.java):



package com.note; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class NoteApplication { public static void main(String[] args) { SpringApplication.run(NoteApplication.class, args); System.out.println("App started...."); } }

Conclusion

Now we have an overview of Spring Boot example when building a @RestController API.

We also take a look at client-server architecture for REST API using Spring Web MVC & Spring Data JPA, as well, we are gooing to continue with Ionic project structure for building a front-end app to make HTTP requests and consume responses.




Post a Comment

Previous Post Next Post


Follow us on facebook