Ref
Ref
VM -
Environment Setup
---------------------
- java 12
- spring tool suite
- node
- VS Code
- mysql community edition + mysql workbench (root)
- docker
GoLang ----
C#/VB ---
| | |
programming Simply the tasks standardise the
process
capabilities
NodeJS
- execution env for js code
VCS Tools
- git
- gitlab
Java
----------
========================
Explore: 1. JVM Architecture
- Class Loader in JVM
- loading, linking, initialization
- execution engine
2. Garbadge Collection
https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/
index.html#t2
3. Naming Conventions
https://www.oracle.com/java/technologies/javase/codeconventions-
introduction.html
========================
- Variables in java
- store values
1. Local Variables
- declared inside a method, constructor
- don't have default values, must be initialized before its use
- memory for all the local variables will be allocated when the
method is invoked, and the detroyed when the method finishes its execution
2. Instance Variables
- declared inside a class, (outside methods)
- whenever a new object is created (using 'new' keyword), memory
for all the instance
variables will be allocated, destroyed when the object is
deleted
- instance variables have default values
- i.e. for numbers = 0
for booleans = false
for reference types = null
- we can use the access modifiers i.e. public, private, protected,
default
3. Static Variables
- declared inside a class, using the 'static' keyword
- only 1 copy of static variable will be allocated per class
- when the class is loaded, memory for static variables will be
allocated
- define the accessiblity using the modifiers i.e. public, private,
protected
Garbadge Collection
- removes the unreferenced objects from the memory
static keyword
- static variables
- static methods
- static class
final keyword
- final variables
- a final variable is constant variables, once the value is assigned
you cannot change it
- final methods
- a final method cannot be overridden in its subclass
- final class
- a final class cannot be subclassed
2. using IO classes
Data types
----------------
primitive data types
- hold / represent values directly
short 2 bytes ..
int 4 bytes ..
long 8 bytes
float 4 bytes
double 8 bytes
char 1 byte
boolean 1 bit
Refernece types
- all the class, interface, enums type variables are called reference
types
- stores ref to the memory
String str;
Employee employee;
Wrapper classes
--------------------
- for each primitive type i.e. int, char etc. there is a corresponding
reference type available i.e. Integer, Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Java Beans
- it is special pojo class that has below requirements
- implements serializable
- all properties / instance variables are defined as private
- public getter/setter methods
- has a no-arg constructor
VO - value object
BO - Business object
- classes that represent business entities
SO - Service object
- classes represents code to perform some business operations
- business logic
Spring Beans
-------------------------------------------
Control statements
- if
if(boolean_expression){
- if - else
if(boolean_expression1){
}else {
- if - else if - else
if(boolean_expression){
}else if(boolean_expression2){
}
..
..
..
else {
case constant1:
statements;
statements;
break;
case constant2:
statements;
statements;
break;
case constant3:
statements;
statements;
break;
..
..
default :
statements;
statements;
}
Looping statements
- while
- do while
- for
- enhanced for loop
Array
---------
- used to store fixed number of elements
- the size of array is fixed
- in java Array is an object
<<data-type>>[] arr-var-name;
int[] numbers;
short[] nums;
String[] names;
double
String[] names;
String [] names;
String []names;
String names[];
c. initialize values
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
java.util.Arrays class
-----------------------------
- This class contains various methods for manipulating arrays (such as
sorting and searching). This class also contains a static factory that allows
arrays to be viewed as lists.
Java OOPS
----------------
Encapsulation
- binding data & logic together
Abstraction
- hiding the complexities from outside world
- hide unnecessary details from the outside world
Inheritance
- a class can be derived from another class
- the members of the parent class are inherited by the child class
- reusability
- maintainability
- extendibility
class Person {
String name;
int age;
Date DOB;
...
//
//
//
}
Polymorphism
- many forms of the same interface depending on the type of object the
variable is pointint to
class Car {
//
//
//
//
//
public void move(){
//
}
}
Class
--------
- a class is a user defined data type
- a class is a blueprint for objects
- ecapsulate data and logic together
Object
--------
- an object is an instance of a class
- using 'new' keyword we can create an object of a class
class Customer {
//static variable
//final variables
//instance variables
//constructors
//instance methods
//abstract methods
//inner class
}
class Product {
class Employee {
Constructor
-------------
- special function / method which has the same name as the class
- this function is invoked only once, whenever the object of this class is
created
- used to initialize values for instance members
- a class can have multiple constructors,
- class should have at least a no-arg constructor
this keyword
--------------
- this() constructor
- it is used to invoke another constructor whithin the same class
- call this 'this()' constructor must be the first line
- this
- used to access the members of the same class
========================
Explore:
- private constructors and its usage
- https://www.baeldung.com/java-private-constructors
==========================
Method Overloading
--------------------
- a class can contain multiple methods with the same name but the
parameteres should be diff
- compile time Polymorphism / static binding
Object class
-------------------
- Object class is by default a super most class for all the classes in java
- everyclass is exclusively subclass of object class
Object
|
------------------------------------------------------------------------------
Student System ArrayList Scanner
..
Employee LinkedList
CustomClass...
**equals() contract
Inheritance
-----------------
- allows to create a subclass, inheriting all the non-private members of
the super class
- using 'extends' keyword we can inherit a class from another class
- inheritance creates is-a relationship
..
..
}
...
..
Account
- accNo
- cusotmerID
- type
- interestRate
- createAcc() / debit() / credit()
|
----------------------------------------------------------------------------
SavingAcc CurrentAcc RecurringDepAcc LoanAcc
-
loanNo
---------------------------
PersonalLoanAcc HomeLoanAcc
a. Composition
b. Aggregation
class Engine {
class Car {
Engine engine;
}
c. Association
class {
instance variables
constructor
instance methods
...
..
}
Interface
--------------------
- similar to a class, but it describes only abstract methods
- interface contains only 'public abstract' methods and 'public static
final' variables
- interfaces are used to define set of requirements that a class has to
implement
- a class must implement an interface and override the abstract methods
**- an interface can extend from several interfaces
interface <<InterfaceName>>{
interface Taxable {
public abstract void calcTax(double intRate);
}
Abstract classes
-------------------
- abstract classes are used to act just a superclass, representing data &
code to be inherited to the subclasses
- using 'abstract' keyword we can declare abstract class
- we cannot instantiate abstract classes
- we cannot create object of abstract class
//instance variables
//static variables
//constructor
//instance methods
public BMWCar(){
Method Overloading
---------------------
- writing multiple methods with same name but diff parameters inside the
same class
Method Overriding
--------------------
- redefining a super class method in the subclass using the same method
signature
- it is used to define child specific behavior of the superclass method
- in method overriding, the name, parameters and return type must be same
-Rules for method overriding
--------------------------------
- 1. only the inherited methods (non-private) can be overridden
Note: private and static method cannot be overridden
public class A {
public void method(){
}
}
public class A {
protected void method(){
}
}
}
}
3. the overridden method must have the exact* method signature in the
subclass
Note: the return type in the overridden method can be a subtype
Abstract Method
----------------------
- a method without definition
- a method declared using 'abstract' keyword
..
interface EmploeyeRepository {
}
public class EmploeyeRepositoryImpl implements EmploeyeRepository{
Collection Framework
--------------------------
- java.util provides various data structures called as collections
- Collection classes offer various DS to allow creating dynamic group of
objects
- collections are set of dynamic and reusable datastructures which are used
to create group of objects
Iterable<E> interface
|
|
Collection<E> interface
|
|-> boolean add(E e)
|-> boolean addAll(Collection<? extends E> c)
|-> void clear()
|-> boolean contains(Object o)
|-> boolean remove(Object o)
|
|
------------------------------------------------------------------------------
List<E> Interface Set<E> Interface Queue<E>
Interface
| | |
| | |--
>LinkedList<E>
ArrayList HashSet |--
>PriorityQueue<E>
|
LinkedList LinkedHashSet
----------------------------------------
Vector TreeSet Deque<E>
Interface BlockingQueue<E> Interface
Stack |
|
|
ArrayBlockingQueue<E>
|
--------------------------------------
Collection<T> interface
- this is the supermost interface in the collection hierarchy that describes
few common methods
- ie. |-> boolean add(E e)
|-> boolean addAll(Collection<? extends E> c)
|-> void clear()
|-> boolean contains(Object o)
|-> boolean remove(Object o)
List<E> Interface
------------------
- models an indexed collection of elements, it allows duplicate elements
- List Implementation classes are ...
1. ArrayList<E>
- internally uses "resizable array" as a datastructure
- the initial capacity of arraylist is 10
- not synchronized
2. LinkedList<E>
- internally uses "double linked list" as a datastructure
- the initial capacity is 0
- good for lists that require freqent insertions, deletions
3. Vector<E>
- internally uses resizable array as a datastructure
- the initial capacity of arraylist is 10
- vector is synchronized, so it is thread safe
4. Stack<E>
- internally uses resizable array as a datastructure
- offers LIFO approach
Set<E> Interface
---------------------
- Set interface models a collection of object that doesn't allow duplicate
elements
- whenever we add a new element, it first compares the element with all
objects (using their equals() and hashCode() ) in the set,
if it doesn't exisit then only the new element will be added
- Note: if you create a set of custom objects, make sure you implement the
hashCode() and equals() methods correctly
- Set Implementation classes --
1. HashSet<E>
- doesn't guarantee order of insertion
- internally uses 'HashTable' structure
2. LinkedHashSet<E>
- stores elements as per the insertion order
- uses 'HashTable+double linked list' data strcuture
3. TreeSet<E>
- maintains the sorted order of elements
- uses 'balanced tree' data structure
Queue<E> Interface
---------------------
- FIFO approach
- it models a collection in the form of a queue that has FIFO approach
| | | | | | |
hashCode()
- its an integer number represening the object;
- The default implementation of the hashCode method is provided by the
Object class,
which returns a unique integer value for each object based on its
memory address.
Natural Ordering
---------------------
- natural ordering is the default ordering of elements while sorting in
array / collection
- if you create a collection of custom objects, and want them sorted, then
you must define
the natural ordering of the elements
interface Comparable<E> {
int compareTo(E obj);
}
class Student implemets Comparable<Student> {
//
//
int marks;
- 2. interface Comparator
- this is used to create external comparators
**Compare Value
- its an integer number
e1.compareTo(e2)
if first object is > second object : return 1 or positive
number
if first object is < second object : return -1 or negative
number
if both are equal : return 0
Create a list
------------------
- non-generic list
- generic list
ArrayList
------------
- ArrayList is one of the implementation class of List Interface
- used to list of objects
- the initial capacity of arraylist is 10
ListIterator
- specific to Lists, used to iterator over lists
- has next() and previous() methods, which allow to iterate in both
directions
Enumeration
- this is also used to iterate over collection
- Collections.enumeration(collection) creates the enumerator
Deque<E> Interface
- represents a double headed queue
1. HashTable<K,V>
- doesn't allow null key
- synchronized
2. HashMap<K,V>
- allows one null key
- not synchronized
3. LinkedHashMap<K,V>
- maintains order of insertion by keys
4. TreeMap<K,V>
- maintains sorted order of keys based on their natural
ordering
Map<Integer, String> map = new HashMap<>()
Map<Integer, String> map = new LinkedHashMap<>()
Map<Integer, String> map = new TreeMap<>()
Collection<T> values()
Set<K> keySet();
entrySet()
Exception Handling
----------------------
- exception is an abnormal event that might occur during the program
execution
- Expcetion
- abnormal event that occurs at run time
i.e. input is invalid, code logic is incorrect, file/db
connection fails, dependencies fails etc.
Throwable
|
---------------------------------------------------------------
Exception Error
| |
|->represents the issues occured at run-time |-> represents
internal system errors (Memory errors, virtual machine error)
| |->
LinkageError
|
---------------------------------------------------------------------------
RuntimeException IOExeption SQLException
EmployeeNotFoundException
|
ArithmaticException
InputMismatchException
ArrayIndexOutofBoundExpception
NullPointerException
IllegalStateException
Unchecked Expcetions
- not necessarily handled by try-catch block
- if there is no handler found, these exception are handled by the "default
exception handler"
- all the "RunTimeExceptions" are unchecked
Checked Expceptions
- must be handled by writing try-catch block or they can be declared to be
thrown
try {
//make a connection to the db
}catch(XYZException ex){
}catch(PQRException ex){
}finally{
//once the operations are done, close the connection
//release the resources
}
try(open the connection to db / file / etc){
}catch(Exception ex){
Multi Threading
----------------
- every java program runs inside a thread, i.e. Main Thread
b. override the 'run()' method to define the task you want to execute
in the thread
b. Create a Thread Object, initialize the runnable task and start the
tread
MyTask task1 = new MyTask();
Thread t1 = new Thread(task1);
Thread synchronization
--------------------------
- implement synchronization
= 1. using the ReentrantLock object (old technique)
= 2. making the methods synchronized
Thread DeadLock
----------
class A {
class B {
synchronized void methodB() {
A.methodA();
}
}
1. java.util.concurrent package
**- provides the utility classes commonly useful in
concurrent programming
i.e. Executors
2. java.util.concurrent.locks package
- provides Lock and Condition implementations
3. java.util.concurrent.atomic package
- provides some data types i.e. AtomicInteger
java.util.concurrent
---------------------------
- provides utility classes that are used to create "thread
pools"
- instead of creating a new thread whenever a task arrives /
every time,
you can use a thread pool which keeps a number of
reusable threads ready for executing the task
- the "Executors" provides various methods to create a pool of
threads
1. Executor
2. ExecutorService
3. ScheduledExecutorService
Future interface:
-------------------
- it is an interface,
- A Future represents the result of an asynchronous computation
interface Future<V>{
V get()
// Waits if necessary for the computation to complete,
and then retrieves its result.
V get(long timeout, TimeUnit unit)
//Waits if necessary for at most the given time for the
computation to complete, and then retrieves its result, if available.
}
Callable interface
------------------
- public interface Callable<V>
- A task that returns a result and may throw an exception
- override the V call() method
}
}
Executor<T> interface
|
|-> void execute(Runnable target)
|
ExecutorService<T> interface
|
|-> void execute(Runnable target)
|-> Future<V> submit(Callable target)
|-> shutdown()
|-> isDone()
|
SchelduledExecutorService<T> interface
|
|-> ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit)
|-> ScheduledFuture<?> scheduleAtFixedRate(Runnable
command, long initialDelay, long period, TimeUnit unit)
|-> ScheduledFuture<V> schedule(Callable<V>
callable, long delay, TimeUnit unit)
JDBC
------------
- java database connectivity
- jdbc is just a specification or standard that every db vendor has to
implement
- every DB Vendor generally provides "driver" to communicate with the
database
- to use the MySQL Database you have to first download the 'mysql-sql-
driver'
- Driver class
- responsible to communiate with the respective database
DriverManager class
- used to create the "Connection" with the database
Connection object
- Connection object represents the connection to the db and used to
send sql commands to the databse
Statement Object
- using the Connection object, we can create 'Statement' objects
- using the 'statement' object we can submit the sql commands / sql
queries to the db
1. Statement
connection.createStatement()
- using statement object we can execute any sql
statement, but it requires lot of concatenation for dynamic values
- we cannot store binary values using object
- the sql query is compiled every time we execute the
statement
2. PreparedStatement
connection.prepareStatement()
- it represents a pre-compiled query, and can also have
paramterised queries
-
3. Callable Statement
connection.callStatement();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =
DriverManager.getConnection("urlOfTheDb","username","password");
rs.getInt(1) rs.getInt("empId")
statement.execute();
connection.close();
---> '101','Vishal','Pune','2000'
'102','Vaibhav','Pune','3000'
'103','Om','Mumbai','1200'
'104','Rohit','Hyderabad','8000'
'105','Mohit','BLR','3500'
Java 8 Features
-------------------
- Functional interfaces
- Lambda expressions
- pre-defined / inbulit functional interfaces
- Predicate
- Supplier
- Consumer
- Function
- Stream API
Functional interfaces
------------------------
- the interface which has only 1 abstract method is called Fuctional
Interface
@FunctionalInterface
interface Taxable {
public double calcTax(double intRate);
}
interface Runnable{
public void run();
}
interface Callable<V>{
public V call();
}
interface Comparable<T>{
public int compareTo(T t)
}
interface Comparator<T>{
public int compare(T t1, T t2);
}
Lambda expressions
-------------------
- offers a simplified way to implement a functional interface
- Predicate
- a functional interface that represents a predicate (boolean-
valued function) of one argument.
Interface Predicate<T>{
boolean test(T t);
}
- Supplier
- Interface Supplier<T>{
T get()
}
- Consumer
interface Consumer<T>{
void accept(T t)
}
- Function
Interface Function<T,R>{
R apply(T t)
}
Stream API
------------------
- a stream represents a sequence of elements and supports sequential as
well as parallel aggregate operations
- process the collections, array and any I/O channel
- Every collection class has the stream() method that returns a 'Stream' of
elements
list.stream();
Stream.of(list);
Stream Operations
---------------------
- intermediate operations
- filter(predicate)
- returns a new stream that consist elements matching a given
condition
- map(function)
- returns a new stream consisting elements which are the result of
the given function
- mapToInt()
- mapToLong()
- mapToDouble()
- sorted()
- limit()
- distinct()
- terminal operations
- collect()
- reduce()
- forEach()
- allMatch()
- anyMatch()
- nonMatch()
- count()
- min(comparator)
- max(comparator)
JDBC challenges
-----------
- heavily dependent on sql queries, you have to write complex queries
- if you make any changes to the model / bo classes, then you have to make
lot of changes in the code as well as in the db tables
- using jdbc as a low level api, there may be lot of code duplications
- Hibernate
- iBatis
- TopLink
Entity
-----------
- entities in jpa are POJO classes
- an entity is an object which is persisted / managed by the JPA providers
@Entity
public class Employee{
@Id
private int empId;
public Employee(){
}
}
EntityManager
----------------
- EntityManager is an object which is used to manage the entities
- EntityManager is responsible to persists the entities in to the database
PersistenceContext
----------------------
- it is a configuration for one or more persistence units
- A persistence unit defines configuration for mapping the java classes
with the database
- the configuration is described in a xml file called "persistence.xml"
- persistence.xml
----------------------
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1"
xsi:schemalocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="my-persistence-unit">
<classes>
//define which java classes you wish to be mapped with the
database
</classes>
<provider>
//provier class name
</provider>
<properties>
//in which db you want to persist the data
//db url
//db username
//db password
</properties>
</persistence-unit>
</persistence>
JPQL
-------
- is object oriented way to commnicate with the database
sql command
"SELECT * FROM employee WHERE sal > 3000"
jpql command
SELECT e.empId, e.name, e.salary FROM Employee e;
Project
---------------
- Entity classes
@Entity
public class Employee{
@Id
private int empId;
public Employee(){
}
}
EntityManager entityManager =
EntityManagerFactory.createEntityManager("my-persistence-unit")
JPA
JPA Provider
Reflection API
-----------------
Design Patterns
- Singleton
- factory
- builder
Types of applications
-------------------------
- web applications **
- REST API applications **
- mobile applications
- event driven applications
- batch applications
- console applications
- game applications
- service worker applications
- Serverless applications
- cloud native applications
- microservice based applications **
overview and features of Java version 9 to 17
-----------------------------------------------
Spring Framework
-----------------------
- helps to build software applications
- The Spring Framework provides a comprehensive programming and
configuration model for modern Java-based enterprise applications - on any kind of
deployment platform.
- Spring makes it easy to create Java enterprise applications
- build
- deploy
- manage the dependencies
- monitor
- debug / troubleshooting
- implement security
- better project structure
1. Spring Core
- Dependency Injection
- a java application is made up of several objects, one object may
be dependent on another object
- 'injecting' means connecting one object to another object
- Containers
- responsible to manage the objects, i.e. instanstiating the
objects, initializaion, destroy the objects
- containers manage the life cycle of objects
1. BeanFactory
- this is a super interface that models various type of
BeanFactory containers
- XmlBeanFactory
2. ApplicationContext
- a super interface that models several
ApplicationContext containers
- ClassPathXmlApplicationContext
- FileSystemXmlApplicationContext
3. WebApplicationContext
- XmlWebApplicationContext
- AnnotationConfigWebApplicationContext
- Spring Bean
- an object that is managed by the container
a. using xml
application-context.xml
--------------------------
<beans>
<bean id="employeeDao"
class="com.demo.dao.EmployeeDao">
</bean>
<bean id="employeeDao"
class="com.demo.dao.EmployeeDao" />
</beans>
b. using java
---------------
@Configuration
public class ApplicationConfig {
@Bean
public Employee createEmployee(){
//java code to create object of type employee
return employee;
}
@Bean
public AccountRepository jdbcAccountRepository(){
JdbcAccountRepositoryImpl
accountRepositoryImpl= new JdbcAccountRepositoryImpl(dataSource);
return accountRepositoryImpl;
}
- Constructor injection
- Setter injection
- Autowiring
- Autowiring is a technique used in Spring to enable automatic
dependency injection. By using it Spring container can autowire relationships
between collaborating beans. It is known as Spring Autowiring.
- Scopes
- scopes define how many instances of the beans should be
created, by default scope is 'singleton'
singleton
prototype
request
session
application
websocket
thread
- 1. constructor
- 2. setter method if property injection is configured
- 3. post initilization
2. Spring AOP
2. Spring Web
- Spring MVC
- Spring REST
3. Spring Data
- Spring Data JPA
- Spring Data MongoDB
-
4. Spring Cloud
- Spring Cloud config
- Spring Cloud Gateway
- Spring Cloud Eureka
- Spring Cloud Circuit Breaker
5. Spring Security
6. Spring Boot
- spring boot provides auto configuration feature that helps in
configuration of beans
- based on presense and absense of some dependencies in classpath /
based on presence and absense of some properties
in application.properties file it automatically creates beans as
per the requirement
- spring-boot-starter-data-jpa
- spring-boot-starter-web
- ..
..
DAO Layer
-------------
- low level jdbc
- spring jdbc template
- ORM Tools i.e. hibernate, iBatis, toplink
- JPA Providers i.e. Hibernate JPA, MyBatis, EclipseLink, OpenJPA
- Spring Data JPA
**Marker Interface
======================
- Explore this concept
QueryDSL
------------
com.demo
SpringDataJPAApplication.java
com.demo.entities
com.demo.services
com.demo.repositories
Entity Relationships
---------------------------
- in java, the relationship between two entities can be described using
'association'
- in relational dbs, the relation between tables are represented using
'referential integrity'
@Entity
public class Order {
*Direction
- Bidirectional
- unidirectional
*Cardinality
- ?
- @one-to-one
- @one-to-many
- @many-to-one
- @many-to-many
Cascading
----------------
- when we parent entity (Order) then it's child entities should
also be saved first (Address)
- when we delete the parent entity (car) then it's child may be
required to be deleted (engine)
- Cascading types
CascadeType.PERSIST
- save() operations cascase to the related entities
- if you save parent entity, it's child will be
automatically saved
CascadeType.MERGE
- the related entities are merged when owning entity is
merged
CascadeType.REFRESH
- refresh() operation
CascadeType.REMOVE
- if the parent entity is removed, it's child will be also
removed
CascadeType.DETACH
- detaches all related entities
CascadeType.ALL
Fetch Policy
--------------
Eagar Fetch
- by default if the relationship is OneToOne / OneToMany
- whenever we query an entity, all its related entities are
also fetched
Lazy Fetch
- if the entities have relationships
- calling the getter method will trigger the fetch operation on
the related entities
Unidirectional OneToOne
-------------------------
public class Order{ public class
Address {
private int id; private int
addId;
private String trackingNo; private String
street, city, state;
private ..
@OneToOne
private Address shippingAddress;
} }
orders_Table
address_table
-------------------------------
-----------------
id tn tp qty fk-add_id add-id
street city state
Bidirectional OneToOne
-------------------------
public class Order{ public class
Address {
private int id; private int
addId;
private String trackingNo; private String
street, city, state;
private ..
@OneToOne @OneToOne
private Address shippingAddress; private Order
order;
} }
orders_Table
address_table
-------------------------------
-----------------
id tn tp qty fk-add_id add-id
street city state FK_order_id
**Though you have bidirectional relationship, having the foregin key column
in both the tables are required
- we can define an 'owner' of the relationship using 'mapped by'
attribute in @OneToOne annotation
**Explore Project Lombok
============================
- https://www.baeldung.com/intro-to-project-lombok
1 *
public class Order { public class OrderItem
{
@OneToOne
private Product
product;
@OneToOne
private Address shippingAddress;
@OneToMany
List<OrderItem> orderItems;
} }
QueryDSL
------------
- Querydsl is a framework which enables the construction of type-safe
SQL-like queries for multiple backends including JPA, MongoDB and SQL in Java
- execute dynamic queries
- to use QueryDSL we need add two dependencies in pom.xml file
- querydsl-jpa
- querydsl-apt
-*querydsl-apt (Annotation Processing Tool)
- it automatically generates Q-Type class for each Entity
- using these qtypes we can generate dynamic quries
@Autowired
private EntityManager entityManager;
query.from(qProduct).where(qProduct.price.between())
Transactions
----------------
TransactionManager
Spring AOP
--------------------
- aspect oriented programming
- allows to perform "cross cutting" operations
Web application
- returns a "view" along with "data"
Web Services
---------------
- returns only "data"
Spring Web
Spring MVC
Spring REST
@Controller
- describes the class as a controller class which can have several
'handler methods'
- is used to create Web Controllers that returns 'views'
@RESTController
- describes the class as a controller class which can have several
'handler methods'
- is used to create REST Controllers that returns 'data'
'handler methods'
- methods mapped with specific http request
- @Getmapping / @PostMapping / @PutMapping / @PatchMapping /
@DeleteMapping
- E-Commerce Application
---------------------------
- Product
- Order
- Cart
- Customer
- ProductCategory
http://localhost:8080/api/products
- Sub-Resource
- the associated entities/DTOs
- i.e. Product --> ProductCategories
http://localhost:8080/api/employees
- HTTP Methods
- GET
- POST
- PUT
- PATCH
- DELETE
200-299 - Success
300-399 - Redirection
400-499 - Client Errors
@PathVariable
- used to bind a route parameter / path parameter with a variable
- http://localhost:8080/employees/101
@RequestParam
- used to bind a query parameters with a variable
http://localhost:8080/employees?city=Pune&salary=27700
@RequestBody
- binds the request payload / request body with the specific java
object/parameter
in the handler methods
Handle Exceptions
-------------------
- local exceptional handler
using @ExceptionHander annotation inside the controller
spring-boot-starter-validation
-----------------------------
- it uses 'hibernate-validator' which allows us to validate java beans
with a
few annotations as below
@NotNull
@NotEmpty
@NotBlank
@Email
@Size
@Pattern
Entity Class
- represents the data you want to persist in the database
DTO classes
- Data transfer object
- represents the request body or the response body
Entity
Product
DTOs
ProductDTO -- represents the fields to be included in the response
structure
ProductCreationDTO - represents the fields for creating a product
Employee Department
OneToMany ManyToOne
Spring Security
------------------
- Spring Security is a powerful and highly customizable authentication and
access-control framework
- Spring Security is a framework that focuses on providing both
authentication and authorization to Java applications.
- you can add the spring-security module to the existing spring boot project
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Authentication
- is a user valid ?
Authorization
- define roles to perform some actions
- manage permissions
1. Basic Authentication
- this is the default configuration in spring security
- by default uses InMemoryUserDetailsManager() to store the
users , we can configure the users either in application.properites
or we can also configure the users in java code (refer to the
UserDetailsService Bean in config class)
2. Database Authentication
- we can create a custom UserDetailsService
- OAuth 2.0 Login - OAuth 2.0 Log In with OpenID Connect and non-standard
OAuth 2.0 Login (i.e. GitHub)
Authentication Providers
---------------------------
Auth-Servers
---------------
Authentication flows
---------------------
- client credentials flow
- password flow
- annonymous token flow
- refresh token flow
-
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
Monolethic Architecture
- If all the functionalities of a project exist in a single codebase
- It becomes too large with time and hence, difficult to manage.
- We need to redeploy the whole application, even for a small change.
- As the size of the application increases, its start-up and deployment
time also increases.
- It is not very reliable, as a single bug in any module can bring down the
entire monolithic application.
Microservices
- also known as the microservice architecture - is an architectural style
that structures an application as a collection of services that are:
- Independently deployable
- Loosely coupled
- Organized around business capabilities
- Owned by a small team
Microservices
- small autonouous services that work together
- break the application into multiple smaller independent parts / modules
that can communiate with each other
- challeges in microservice
------------------------------
1. how to break the application into smaller parts?
- define the business functinalities and each service should be
responsible to implement those functionalities
Interservice communication
------------------------------
a. Synchronous
1. using RestTemplate
- **Note: under maintainance at the moment
2. using WebClient
- use this class to make sync as well as async operations
b. Asynchronous
- Apache Kafka
- RabbitMQ
- AWS SQS / AWS Kinesis
- GCP Pub-sub
- Azure Service Bus
- ..
- retry pattern
- Bulkhead Pattern
Docker
-----------
- tool to isolate your application code and execute your application in the
form of
distributed system
- it also helps to automate the deployment
- it runs your application inside a "sandbox/container" that runs on any
operating system
Docker Image
----------------
- iso image, a self execuatable package including your code + runtime +
libraries required
to run your code
Docker Container
-------------------
- a container is an instance of the docker image which executes the
application
in an isolated environment on any platform
jenkins
-----------
- Jenkins is a self-contained, open source automation server which
can be used to automate all sorts of tasks related to building,
testing, and delivering or deploying software.
department-service
- port : 8081
employee-service
- port : 9091
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/suhvishalp/parent-demo-repo.git
git push -u origin main
REF: https://github.com/RameshMF/BookStoreApp-Distributed-Application
Group 1 - Rohit-Team
Rohit - https://github.com/RohitBikkad/Group1-Rohit-Product-Service
Vaibhav - https://github.com/vaibhavRpisal/Group1-vaibhav-order-service
Pranjal - https://github.com/Pranjalkoli26/Group1-Pranjal-User-Service
Samrat - https://github.com/SamratIngle/Group1-Samrat-Payment-service
GROUP2-SUYASH-TEAM
Suyash : https://github.com/Suyash777/group2-suyash-product-service.git
Om : https://github.com/omshigwan/group2-om-user-service.git
Skanda : https://github.com/19ska/group2-skanda-order-service.git
Mohit : https://github.com/mohitm018/group2-mohit-payment-service.git
Group3-Adarsh-Team
Adarsh:- https://github.com/adarskumar1205/Group3-Adarsh-Product-Service
Yashasvi:- https://github.com/paunikaryashasvi/Group3-yashasvi-order-service
Pranisha:- https://github.com/Pranisha01/Group3-Pranisha-User-Service
Onkar:- https://github.com/Onkartayde21/Group3-Onkar-Payment-Service