Sunday, June 19, 2022

Hiberante

 Map entity to multiple tables

  • Annotate table with @SecondayTable(name ="author_details") annotation.
  • Provide table name in @Column(table ="author_details")  annotation
  • Benefit to split entity and its details into separate tables. Like author and author details
    Reference

Difference between First level and Second Level cache


KeyFirst level cacheSecond level cache


Basic 

First level cache is a session level 

cache and it is always associated with 

session level object

Second level cache is session factory level 

cache and it is available across all sessions


Enabled 

It is enabled by default.

It is not enabled by default.


Availability 

It is available for a session 

It is available across all session.


Configuration 

No Extra configuration required 

We have to decide  which
concurrency strategy to use and
also need to configure cache
expiration 
and physical cache attributes.


Different Entity states in JPA and Hibernate
























N+1 Problem

  • there is car and wheel table --> SELECT * FROM Cars;
  • in order to fetch wheel car we will hit db  --> SELECT * FROM Wheel WHERE CarId = ?
  • Solution to this JOIN tables (or Entity Graph)

Reference : Stackoverflow
Reference : Entity Graph 


Hibernate Fetch types

  • FetchMode JOIN : Eager loading which loads all the collections and relations at the same time.
  • FetchMode SELECT(default) : Lazy loading which loads the collections and relations only when required.
  • FetchMode SELECT with Batch Size : Fetch upto “N”collections or entities(“Not number of records”)
  • FetchMode SUBSELECT : Group the collection of an entity into a Sub-Select query.
Reference : link
Reference : Baeldung

Load() vs Get()

load()get()
Only use load() method if you are sure that the object exists.If you are not sure that the object exist, then use one of get() methods.
load() method will throw an exception if the unique id is not found in the database.get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won't be hit until the proxy is first invoked.get() will hit the database immediately.

Reference : link

Dirty Checking

  • Hibernate has a feature of checking all managed entity properties. Whenever an entity is loaded through hibernate, it makes an additional copy of that whole entity object along with the all entity's property values
  • So even if only one property of the persistent object is changed, Hibernate will still check all managed entities. It detects which objects have been modified and then calls update statements on all updated objects.
  • Hibernate monitors all persistent objects. At the end of a unit of work, it knows which objects have been modified. Then it calls update statement on all updated objects. This process of monitoring and updating only objects that have been changed is called automatic dirty checking in hibernate.
  • Within the Persistence Context, Hibernate has a copy of all persistent objects that were loaded from the database. It compares these persistent objects with these objects to detect the objects that have been modified or are dirty. This is the default implementation.
Reference : link

Query Cache and Second Level Cache

Second level cache look likes(key value)
*---------------------------------------------*
|          Person Data Cache                     |
|----------------------------------------------|
| 1 -> [ "John" , "Q" , "Public" , null ]   |
| 2 -> [ "Joey" , "D" , "Public" ,  1   ]    |
| 3 -> [ "Sara" , "N" , "Public" ,  1   ]    |
*---------------------------------------------*

Query cache look likes (key value)
*-------------------------------------------------------------------- *
|                       Query Cache                                                 |                     
|----------------------------------------------------------|-----------
| ["from Person where firstName=?", ["Joey"] ] -> [1, 2] ]  |
*---------------------------------------------------------------------*

What is the relation between the two caches?
  • If a query under execution has previously cached results, then no SQL statement is sent to the database. Instead the query results are retrieved from the query cache, and then the cached entity identifiers are used to access the second level cache.
  • If the second level cache contains data for a given Id, it re-hydrates the entity and returns it. If the second level cache does not contain the results for that particular Id, then an SQL query is issued to load the entity from the database.
Reference : link


Hibernate Inheritance Mapping 

  • MappedSuperclass – the parent classes, can't be entities
  • Single Table – The entities from different classes with a common ancestor are placed in a single table.
  • Joined Table – Each class has its table, and querying a subclass entity requires joining the tables.
  • Table per Class – All the properties of a class are in its table, so no join is required.
Reference : link


Monday, June 13, 2022

Spring Transaction Management

 

  • Transaction Propagation : Propagation defines our business logic's transaction boundary. Spring manages to start and pause a transaction according to our propagation setting. (in other words  : Defines how transactions relate to each other)
    • REQUIRED : Code will always run in a transaction. Creates a new transaction or reuses one if available.
    • REQUIRED_NEW : Code will always run in a new transaction. Suspends the current transaction if one exists.
    • SUPPORTS
    • MANDATORY
    • NEVER
    • NOT_SUPPORTED
    • NESTED

  • Transaction  Isolation :  solation is one of the common ACID properties: Atomicity, Consistency, Isolation, and Durability. Isolation describes how changes applied by concurrent transactions are visible to each other. (in other words :  Defines the data contract between transactions)
    Isolation Levels
    • DEFAULT 
    • READ_UNCOMMITTED : Allows dirty reads
    • READ_COMMITTED :  Does not allow dirty reads
    • REPEATABLE_READ : If a row is read twice in the same transaction, the result will always be the same 
    • SERIALIZABLE : Performs all transactions in a sequence
Each isolation level prevents zero or more concurrency side effects on a transaction:
  • Dirty read: read the uncommitted change of a concurrent transaction
  • Nonrepeatable read: get different value on re-read of a row if a concurrent transaction updates the same row and commits
  • Phantom read: get different rows after re-execution of a range query if another transaction adds or removes some rows in the range and commits

  • References

    Baeldung : link 

    Stackoverflow : link

    Transactions with Spring and JPA : link


    Saturday, June 11, 2022

    Design Patterns - Singleton


    • Eager - thread safe but can be broken with below techniques
      • reflection
      • object cloning
      • serialization/deserialization
    • Lazy - in multithread environment can be archived with below techniques
      • synchronize whole method
      • Double checked locking - synchronize inside method + volatile
      • Bill Pugh method - static Holder Class
      • Enum method

    Referances

    Singleton all scenarios : link  

    Baeldung : link 

    Saturday, March 12, 2022

    Spring Web MVC

    Front Controller : 

    the concept of the Front Controller in the typical Spring Model View Controller architecture

    At a very high level, here are the main responsibilities we're looking at:

    • Intercepts incoming requests
    • Converts the payload of the request to the internal structure of the data
    • Sends the data to Model for further processing
    • Gets processed data from the Model and advances that data to the View for rendering


    • DispatcherServlet plays the role of the Front Controller in the architecture.
    • The diagram is applicable both to typical MVC controllers as well as RESTful controllers
    • MVC applications are not service-oriented hence there is a View Resolver that renders final views based on data received from a Controller
    • RESTful applications are designed to be service-oriented and return raw data (JSON/XML typically). Since these applications do not do any view rendering, there are no View Resolvers – the Controller is generally expected to send data directly via the HTTP response

    MVC Controller : 

    @Controller
    @RequestMapping(value="Test")
    public class TestController{
    .....
    }

    Rest Controller :

    Maven Dependencies :  spring-web,  spring-webmvc,  jackson-databind

    @Controller
    public class TestController{
       @GetMapping(value = "/student/{studentId}")
        public @ResponseBody Student getTestData(@PathVariable Integer studentId) {
            Student student = new Student();
            student.setName("Peter");
            student.setId(studentId);

            return student;
        } 
    }
    @ResponseBody annotation on the method – which instructs Spring to bypass the view resolver and essentially write out the output directly to the body of the HTTP response.

    Spring Boot - @RestController

    @RestController
    public class RestAnnotatedController {
        @GetMapping(value = "/annotated/student/{studentId}")
        public Student getData(@PathVariable Integer studentId) {
            Student student = new Student();
            student.setName("Peter");
            student.setId(studentId);

            return student;
        }
    }
    @RestController annotation from Spring Boot is basically a quick shortcut that saves us from always having to define @ResponseBody. Help by pass view rendering stage and directly writing response to HTTP response body

    @RequestMapping
    the annotation is used to map web requests to Spring Controller methods

    Example 1 : Request Mapping with by path and HTTP method

    @RequestMapping(value = "/ex/foos", method = POST)
    @ResponseBody
    public String postFoos() {
        return "Post some Foos";
    }


    Example 2 : Request Mapping and HTTP header

    @RequestMapping(
      value = "/ex/foos", 
      headers = { "key1=val1", "key2=val2" }, method = GET)
    @ResponseBody
    public String getFoosWithHeaders() {
        return "Get some Foos with Header";
    }


    Example 3 : Mapping media types produced and consumed by controller

    @RequestMapping(value="/method6",
    produces={"application/json","application/xml"},
    consumes="text/html")
    @ResponseBody
    public String method6(){
    return "method6";
    }
    Above method can consume message only with Content-Type as text/html and is able to produce messages of type application/json and application/xml.


    Example 4 : Request Mapping with Path Variable

    @RequestMapping(value = "/ex/foos/{fooid}/bar/{barid}", method = GET)
    @ResponseBody
    public String getFoosBySimplePathWithPathVariables
      (@PathVariable long fooid, @PathVariable long barid) {
        return "Get a specific Bar with id=" + barid + 
          " from a Foo with id=" + fooid;
    }

    Example 5 : Request Mapping with Request Parameters

    @RequestMapping(value = "/ex/bars", method = GET)
    @ResponseBody
    public String getBarBySimplePathWithRequestParam( @RequestParam("id") long id) {
        return "Get a specific Bar with id=" + id;
    }

    http://localhost:8080/spring-rest/ex/bars?id=100

    Example 6 :  Request Mapping with Fallback

    @RequestMapping(
      value = "*", 
      method = { RequestMethod.GET, RequestMethod.POST ... })
    @ResponseBody
    public String allFallback() {
        return "Fallback for All Requests";
    }

    @RequestMapping New Shortcut Annotations

    • @GetMapping
    • @PostMapping
    • @PutMapping
    • @DeleteMapping
    • @PatchMapping



    Reference 1 :  Baeldung
    Reference 2 :  Journal Dev


    Saturday, February 19, 2022

    Object Oriented Programming

     Advantages of OOP :

    • Reusability
    • OOPs is very helpful in solving very complex level of problems.
    • Highly complex programs can be created, handled, and maintained easily using object-oriented programming.
    • OOPs, promote code reuse, thereby reducing redundancy.
    • OOPs also helps to hide the unnecessary details with the help of Data Abstraction.
    • OOPs, are based on a bottom-up approach, unlike the Structural programming paradigm, which uses a top-down approach.
    • Polymorphism offers a lot of flexibility in OOPs.

    Properties of OOP :

    • Encapsulation
    • Data abstraction
    • Polymorphism 
    • Inheritance 

    Encapsulation vs Data Abstraction

    Encapsulation is the packing of "data" and "functions operating on that data" into a single component and restricting the access to some of the object's components. Encapsulation means that the internal representation of an object is generally hidden from view outside of the object's definition.

    Abstraction is a mechanism which represent the essential features without including implementation details.

    Encapsulation:-- Information hiding.
    Abstraction:-- Implementation hiding.


    Polymorphism 

    Polymorphism is composed of two words - “poly” which means “many”, and “morph” which means “shapes”. Therefore Polymorphism refers to something that has many shapes.

    Types of Polymorphism 




    Compile time polymorphism : method overloading

    Runtime polymorphism : method overriding 


    Reference :