Java Spring Boot in Farsi

ویدئوهای توصیفی جاوا اسپرینگ بوت

فیلم های توصیفی زیر از پروژه ها ی جاوا اسپرینگ بوت استفاده می کنند تا مثال ها را نشان دهند. یکی از اصلی ترین پروژه ها، پروژه ی زیر هست که به صورت فایل زیپ قابل دانلود است و قابل تطبیق با توضیحات است.

Download WorkSuggest Project version 1.9 — Zip file

Video 1 — ویدئوی اول

About Java Spring Boot using an interface

Overview:

– create Controller, include URLs including REST endpoints
using @GetMapping, @PostMapping, @DeleteMapping, @PutMapping
– creat right packages
(common ones are entity, repository, service, controller)
– create an interface
(in this application we have 3 interfaces
one for database interactions,
one for booking, and one for booking service)

interface includes the name and type of methods
you will implement in a class

Video 2 — ویدئوی دوم

Spring CRUD and SQL interactions

Overview:

CrudRepository: Simplification of Create-Read-Update-Delete interactions

<S extends T> save(S entity) – Used to save a single entity at a time.
Iterable<S> saveAll(Iterable<S> entities) – we can save multiple entities at a time.
Optional<T> findById(ID id) – use to get entity basis of id.
boolean existsById(ID id) – used to check whether an entity is already exited in DB for given Id.
Iterable<T> findAll() – find all entity of paricular type.
Iterable<T> findAllById(Iterable<ID> ids) – return all entity of given ids.
long count() – returns the number of entities
void deleteById(ID id) – delete the entity on basis of id
void delete(T entity) – delete the entity which one we are passing.
void delete(Iterable<? extends T> entities) – delete multiple entities which we are passing.
void deleteAll() – delete all entities.

(source: https://www.netsurfingzone.com/jpa/crudrepository-methods-example/ )

@Repository

@Transactional(readOnly = true)
enabling update and insert

@Modifying (see the class TaskStatusRepository.java)

Video 3 — ویدئوی سوم

Database Tables And The Respective Entities In Java Spring Boot

Overview:

We create a database table and define its columns as variables in the entity

Entities represent database tables

These are entities that we have in our Java Spring Boot application.
They will have services and repositoies associated with them.

A set of annotations clarify the class, including Lombok annotations.
The @Entity annotation is important

The @Table(name=”tablename”) is an example of an annotation to give
tablename.

The @Id annotation defines the id field

The @GeneratedValue annotation may be applied to a primary key property

We can define the relationship between tables using
@ManyToOne, @OneToMany, and @ManyToMany annotations.

 

Video 4 — ویدئوی چهارم

One To Many relation description

Overview:

– ٍExample: Task and TaskStatus. One task, many task statuses
– See in the database the foreign key relation
available in TaskStatus table

Example:

– Task.java
@OneToMany(mappedBy = “task”, cascade = CascadeType.ALL)
private Set<TaskStatus> taskStatuses;

– TaskStatus.java
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = “task_id”)
private Task task;

CascadeType
cascade = CascadeType.ALL
https://www.baeldung.com/jpa-cascade-types

FetchType
fetch = FetchType.LAZY
https://www.baeldung.com/hibernate-lazy-eager-loading

Video 5 — ویدئوی پنجم

Many To Many relation description

Overview:

– ٍExample: Task and Person.
One task, many persons
One person, many tasks

– join table is the name of the two tables concatenated with _

– person side is owning side. has @JoinTable annotation

– https://stackoverflow.com/questions/36803306/should-jointable-be-specified-in-both-sides-of-a-manytomany-relationship

– should add on owning side

Video 6 — ویدئوی ششم

Thymeleaf basics

Overview:

– Java EE templating possible with JSP, JSF (used to be in focus)
– Templating is a focus with Java EE, Java Spring Boot
– Thymeleaf: reviewing: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
– the generalities in an application:
<html xmlns:th=”http://www.thymeleaf.org”>
<p th:text=”#{home.welcome}”>Welcome to our grocery store!</p>
– fragments, variables, iterations, if statements, html tag values

– have fragments
fragment:
<div th:fragment=”adminDetailBar”…
use it:
<div th:insert=”fragments/general.html :: adminDetailBar” >This was admin bar</div>
<div th:replace=”fragments/header.html :: header-css”/>

th:insert is the simplest: it will simply insert the specified fragment as the body of its host tag.

th:replace actually replaces its host tag with the specified fragment.

th:include is similar to th:insert, but instead of inserting the fragment it only inserts the contents of this fragment.

– if-statements
<div th:if=”${user.isAdmin()} == false”> …

– variables
th:text=”${message}
@{${baseURL} + ‘/admin’}

– iteration
<tr class=”dataRow” th:each=”iter : ${worksuggests}”>
<td th:text=”${iter.worksuggest_id}”>id</td>
<td><a th:href=”@{${baseURL} + ‘/admin/worksuggestlist/’ + ${iter.worksuggest_id} + ‘/remove/’ }”

– switch statements
<div th:switch=”${user.role}”>
<p th:case=”‘admin'”>User is an administrator</p>
<p th:case=”#{roles.manager}”>User is a manager</p>
</div>

– th:value, th:text, … (see section 5.2 Setting value to specific attributes)

<select name=”worksuggestlistid”>
<option value=”” text=”Select the Work Suggestion List for this task” selected=”selected”></option>
<option th:each=”iter : ${worksuggests}”
th:value=”${iter.worksuggest_id}”
th:text=”${iter.title}”></option>
</select>

Video 7 — ویدئوی هفتم

Description for several parts of Spring Boot Security

Overview:

pom.xml file

dependencies

Spring Security is a Spring Framework feature

error handler implements AccessDeniedHandler

UserDetailsService features among others
User, UserDetails

AuthenticationSuccessHandler

WebSecurityConfigurerAdapter

Video 8 — ویدئوی هشتم

Spring Boot Security with basic DataSource

Overview:

Spring Boot makes Java app development easy for the web

A set of jar files — dependencies

test dependecies, application server dependecy (usually minimized in Spring Boot), usual dep.

here: mysql dependency, spring-boot-starter-security, //spring boot starter data jpa

a series of useful classes as autowires

ConfigureAuthentication
configure (WebSecurity web)
configure (HttpSecurity http)
configureGlobal

NoOpPasswordEncoder — various password encoders

now to log-in there will be credential check that comes from db

application.properties has db detail

which tables? authorities, users;

let’s see the database

see users…

log in

example tutorials. keywords: jdbc authentication in Spring Boot

Video 9 — ویدئوی نهم

Spring Boot Session with Redis

Overview:

– Session: keeping user detail while user interacts with our application
– set redis as datasource via application.properties
– download Redis, start its server otherwise Spring Boot can’t connect
– See Redis folder structure
– start redis-server.exe
redis-server.exe –maxheap 1024M
– start redis CLI

http://localhost:3306/
http://localhost:6379/
http://localhost:8080/

JavaInUse example

HttpSession variable as argument in main URL
session.getAttribute

HttpServletRequest
in persistMessage URL
request.getSession.setAttribute

also in URL for destroying the session

demo and the controller
http://localhost:8080/package1_war_exploded/

Video 10 — ویدئوی دهم

using BCrypt in Spring Boot

Overview:

============== SpringSecurityConfig file ============
SpringSecurityConfig has a configure method that takes in auth with the class
AuthenticationManagerBuilder.
It sets the auth’s authenticationProvider to use authProvider

authProvider itself is a bean of type DaoAuthenitcationProvider.

The bean authProvider is of type DaoAuthenticationProvider which is using the passwordEncoder.
It also uses a UserDetailsService

PasswordEncoder is set in the SpringSecurityConfig. It is set to return BCryptPasswordEncoder

PasswordEncoder is autowired in UsersService

User Service:
We can work with User Service which has several User interaction methods.
One of these is “saveUser”. Here in this method we can save our userpasswords with the password encoder
if we include it in our User Service class ile.
saveUser in UsersService uses the passwordEncoder (throught Autowire) to encode and set the password

User Entity:
Users entities has username, password, enabled.

whereever we need to interact with the user such as in UserService’s saveUsers we save with encyrption

for reading the password we just pass in password as is in database
in the user builder in userDetailsServiceImpl

=========== userDetailsServiceImpl ============
builder is spring based. Therefore its password field works with the encrypted password that we pass in

we are returning userDetailsService implementation as an autowire that works in
the SpringSecurityConfig and the DaoAuthenticationProvider.

Video 11 — ویدئوی یازدهم

Spring Boot Angular app description

Overview:

Angular – Interactions: drag and drop

Spring Boot:
Entities: database table structures
Repositories: interactions with the database
Services: contact between (interactions with database) and the user requests (controller)

returning JSON format results

demo of RESTpoints

Interacting with data via Spring Boot

These are links to resources that describe how to access data via queries in a Spring Boot application. The Spring repository to work with will extend the Crud repository and will include methods that have annotations such as @Query and @Modifying. The queries can use JPQL or be native SQL.

Baeldung’s Tutorial on Spring JPA Data @Query:
https://www.baeldung.com/spring-data-jpa-query

App developer’s blog on the @Query annotation
http://www.appsdeveloperblog.com/spring-data-jpa-native-sql-query/

StackOverflow’s Inserting into Spring data
How to insert into db in spring-data?

Working with Thymeleaf and Templating issues for front end development

Here are starting points to work with Thymeleaf templates and some issues revolving the front end development


Thymeleaf — A Templating alternative with Spring Boot:
https://www.thymeleaf.org/

To include HTML or dynamic HTML parts into a Thymeleaf template, Thymeleaf uses the concept and term: “fragments”, which assists with inserting or replacing parts of your pages with other parts. Here is a tutorial:
https://www.baeldung.com/spring-thymeleaf-fragments

Validating The Form entries that will be sent to the Spring Boot application:
https://stackoverflow.com/questions/22658572/spring-annotations-modelattribute-and-valid

Using Constraints with form input
https://javaee.github.io/tutorial/bean-validation002.html

Other two suggested links:
https://docs.jboss.org/hibernate/validator/5.3/reference/en-US/html_single/#validator-gettingstarted-uel

https://www.baeldung.com/spring-mvc-custom-validator

Spring Boot + Thymeleaf HTML Form Handling Tutorial
https://medium.com/@grokwich/spring-boot-thymeleaf-html-form-handling-part-2-b4c9e83a189c

Spring Boot + Thymeleaf CRUD Example
https://www.dariawan.com/tutorials/spring/spring-boot-thymeleaf-crud-example/