Showing posts with label OOD. Show all posts
Showing posts with label OOD. Show all posts

Monday, October 12, 2015

Hibernate mapping with Annotation


This is a simple example of mapping a java domain class with a relation using JPA annotation and Hibernate.

Hibernate can be mapped in 2 ways.
  • With an XML mapping file(.hbm file)
  • With Annotation
Description
   We use JPA as Annotation specification and Hibernate as the provider.

Steps

  • Create a java project using Maven in Eclipse and update the pom file

Refer: Hibernate environment setup with maven using Eclipse


  • Create the domain class and annotate using JPA annotation
@Entity - Denotes that instances of this class are persistent with a DB
@Table - Denotes that name of the corresponding table in DB is STUDENT if not used this annotation, table name would be the same as class name(Hence, here it would be Student)
@Id - This field will be the Primary Key column
@Column - Denotes that this will be a column in the table

Mapping can be done for member variables or/and their corresponding getter methods.

package com.sajith.domain;

import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Student Domain class
 *
 */

@Entity
@Table(name="STUDENT")
public class Student {

 
 private int studentId;
 
 private String studentName;
 
 private String studnetCity;

 @Id
 @Column(name="ID")
 public int getStudentId() {
  return studentId;
 }

 
 public void setStudentId(int studentId) {
  this.studentId = studentId;
 }

 @Column(name="CITY")
 public String getStudnetCity() {
  return studnetCity;
 }

 public void setStudnetCity(String studnetCity) {
  this.studnetCity = studnetCity;
 }

 @Column(name="NAME")
 public String getStudentName() {
  return studentName;
 }

 public void setStudentName(String studentName) {
  this.studentName = studentName;
 }

}


  • Create the Hibernate configuration file
  When you use annotation instead of XML mapping only change will be instead of <mapping resource>
<mapping class> attribute.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">sajith</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property>
        <property name="hibernate.connection.username">sajith</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="show_sql">true</property>
        <property name="hbmdl.auto">update</property>
        <mapping class="com.sajith.domain.Student"/>
    </session-factory>
</hibernate-configuration>


  • Create the Util class

package com.sajith.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

 private static final SessionFactory sessionFactory = buildSessionFactory();
 
 private static ServiceRegistry serviceRegistry;

 private static SessionFactory buildSessionFactory() {
  
   Configuration configuration = new Configuration();
   configuration.configure();
   serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
          configuration.getProperties()).build();
  
  return configuration.buildSessionFactory(serviceRegistry);
       
  
 }

 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }

 public static void shutdown() {
  // Close caches and connection pools
  getSessionFactory().close();
 }
 
}

  • Create the main App class
 
package com.sajith;

import org.hibernate.Session; 
import com.sajith.domain.Student;
import com.sajith.util.HibernateUtil;

public class App {

 
 public static void main(String[] args) {
  
 
  Session session = HibernateUtil.getSessionFactory().openSession();

  session.beginTransaction();
   
  Student student1 = new Student();
  
  student1.setStudentId(1);
                student1.setStudentName("Sanya Fernando");
                student1.setStudnetCity("Kandy");
 
  session.save(student1);
  session.getTransaction().commit();
  
  
 }
 
}
 
  • Run the App file





Wednesday, September 24, 2014

Design Patterns in OOD/OOP

Definition

It is a collection of reusable solutions identified by software professionals through lesson learned and best practices to a commonly reoccurring problem in software design.

In Object Oriented Design ,Software Design Patterns are derived from Object Oriented Concepts and Principles.

Invention

Commonly called that Gang of Four are founders of design patterns

Intention

Mainly focuses on designing and developing easy to maintenance, flexible, low coupling and high cohesion applications.

Types
  1. Object Oriented Design Patterns - How the Classes and Objects are organized to develop an easy maintenance system.
  2.  Architectural Design Patterns  - How the Components (Collection of Classes) are arranged in different tiers across an enterprise application to develop an easy maintenance and scalable system.

Object Oriented Design Patterns

    Categorized into 4 sub categories.
  1. Creational  Patterns - Focuses on new object creation.
  2. Structural Patterns - Focuses on simple way to realize relationships between entities.
  3. Behavioral Patterns - Focuses on common communication relationships between objects.
  4. Concurrency Patterns - Focuses on the multi-threaded programming paradigm.

Architectural Design Patterns

  Categorized into 3 sub categories.
  1. Presentation Tier Patterns - Focuses on arranging components in front-end.
  2. Business Tier Patterns - Focuses on arranging components and interaction with Presentation Tier.
  3. Integration Tier Patterns  - Focuses on arranging components in back-end and interaction with Business Tier.

Sunday, September 7, 2014

OO Principles


Object Oriented principles (OOP) differ from Object Oriented concepts (OOC). Yet OOP derive from OOC

4 object oriented concepts are:

Abstraction
Encapsulation
Inheritance
Polymorphism

Whereas, 5 OOPs  are defined as SOLID.

 S - Single Responsibility Principle
 O - Open Closed Principle
 L - Liskov Substitution Principle
 I - Interface Segregation Principle
 D - Dependency Inversion Principle


Single Responsibility Principle -

A Class should be designed in a way that only performs well-defined one task only. It should not couple with multiple tasks. In nutshell, Class should be high cohesion. 

If a Class performed multiple tasks and there was a requirement change, the class would need to be changed multiple places and times due to overlapping of responsibilities. This leads to maintenance difficulty.The changes will occur in minimal places without affecting rest of the codes

However, this does not mean that the class must only contain one attribute and method. A class can contain multiple attributes and methods but collaboratively it satisfies well-defined one requirement only. On the other hand,  the more functionalities are added to a class the more difficult in testing as well.


 Following class has more than one responsibility to change the code.

1. If the content changes from String to HTML 
2. If the message format changes



Good design


We create a separate  interface called Content and inject the appropriate type at run time.


Open Close Principle

This simply says class is closed to modification but open for extension.

Take the above example. Lets say we want to process the content of the message and there are multiple message types such as SMS, Email, Voice mail. Due to different types of Messages, the processing functionality should be different from each other. Also, in the future new message types and processing requirements could be added.

If we implemented a processing controller class to handle above requirement, it would be difficult to change when new message type is added.



In above code, the controller class has the knowledge of how to process a message. And if new message type is added, the above code needs to be changed incorporating a new process method and modifying the condition block.

The better approach is the process method itself contains the process and injects to the controller.



Here Interface Content defines method signature of process and its concrete classes hold the implementations. Whenever new message type is added the developer will implement the process in new message type class and no need to change the ContentProcessing.

Liskov Substitution Principle

Derived types must be completely substitutable for their base types. Classic example is Rectangle, Square relationship.

Square is a type of Rectangle. Which means Rectangle is the super class and its sub class Square can substitute it.

Following code shows a bad design and an incorrect output is generated.

class Rectangle {
     int width;
     int height;

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public int getArea() {
        return width * height;
    }
}

class Square extends Rectangle {
    public void setWidth(int width) {
        this.width = width;
        this.height = width;
    }

    public void setHeight(int height) {
        this.width = height;
        this.height = height;
    }

}

public class LspTest {

    private static Rectangle getNewRectangle() {

        return new Square();
    }

    public static void main(String args[]) {
        Rectangle r = LspTest.getNewRectangle();

        r.setWidth(5);
        r.setHeight(10);
// expected output is = 50 , actual output = 100
    }

}

Interface Segregation Principle

Clients should not be forced to depend on interfaces that they don't use. When we extend a class or implement an interface owing to inheritance nature of Object Oriented Languages leads to high coupling design. Therefore, create separate interfaces representing different behaviours.



In above situation both Dog and Cat confirm and override super class Mammal behaviour. However some mammals do not breed rather lay eggs like Platypus. In such situation the above hierarchy will break.


Here, we do not enforce to implement unnecessary behaviour rather create separate interfaces according to the concrete class requirements.


Dependency Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstractions should not depend on details. Details should depend on abstractions.

 It is a type of Inversion of control(IOC). here, we prefer aggregation to inheritance due to low coupling between classes. We use abstraction and polymorphism when referencing.


 The problem with the above code when a dog makes a different sound, how to incorporate it with existing design. The solution is to make Sound an interface and create separate concrete classes for different noises.

public interface Sound {
    void makeSound();
}

class Bark implements Sound {
    @Override
    public void makeSound() {
        // barking
    }
}

class Howl implements Sound {

    @Override
    public void makeSound() {
        // howling
    }
}

class Dog {

    private Sound sound;

    public void bark(Sound sound) {
        sound.makeSound();
    }

    public void setSound(Sound sound) {
        this.sound = sound;
    }
}