Wednesday, October 26, 2016

Why DDL is faster than DML?

DDL is always and always faster than DML.

After firing DDL statement we cannot fire rollback command, but in DML we can.

The reason being for DML; Oracle stores records in Redo Log Files; and copies them back during rollback.

For DDL statements; Log Files are not maintained.



One common question always asked is this -> What is the difference between Delete and Truncate?

Difference 1: Truncate (DDL) is faster than Delete (DML)

Difference 2: Delete can be rollbacked whereas Truncate can't.

Reason being Redo Log Files not maintained for Truncate.

Indexing in Oracle

Ever wondered what Indexing actually does :)

An index is a performance tuning mechanism that allows faster retreival of records.

Searching an indexed table is always faster than a normal table since indexing keeps the records sorted (B-Tree).

In normal search oracle has to scan the entire table, but in an indexed table there is no need to scan the entire table since the records are already sorted.


Index on Single column ->

CREATE INDEX PIndex ON TableName (ColumnName)


Index on multiple columns->

CREATE INDEX PIndex ON TableName (ColumnOne, ColumnTwo)


Following query fetches only the user defined Indexes->

SELECT
i.INDEX_NAME, i.TABLE_NAME, ic.COLUMN_NAME, ic.COLUMN_POSITION, UNIQUENESS
FROM
USER_INDEXES i JOIN USER_IND_COLUMNS ic ON i.INDEX_NAME = ic.INDEX_NAME
WHERE
i.TABLE_NAME IN (SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER='CITI_AMWS_CLUSTER_162');


Above you need to enter OWNER = schemaName.


To fetch all available Indexes use this ->

SELECT * FROM ALL_INDEXES;


Following DDL statement can be used to rebuild in Indexes.

ALTER INDEX index_name REBUILD;


Drop Index ->

DROP INDEX index_name;

Tuesday, October 18, 2016

Algorithms & Data Structures - Some Definitions

Variables - Placeholders for holding data.

Data Types - Set of data with predefined values.

Data Structure - A special format for organizing and storing data.

Algotithm - Step by Step instructions to solve a given problem.

Recursion - Any function which calls itself is called recursive. It is important to ensure that the recursion terminates. Each time the function should call itself with a slightly simpler version of the original problem. 

Wednesday, October 12, 2016

Hibernate load() and get() methods

Hibernate load() and get() methods->

1) Both are from session interface and we call them as session.get() and session.load().

2) When we call session.load() method, it will always return a proxy object - hibernate prepares
     a fake object without hitting the database.
              It will hit the database only when we try to retrieve the properties of the object. If that   
     object is not found it will throw a ObjectNotFoundException.

3) When we call session.get() method, it will hit the database immediately and returns the original
     object. If the row is not available in the database, it returns null.

Thursday, October 6, 2016

Eager and Lazy Loading in Hibernate

Eager Loading - Means loading an object with its entire dataset in one go. This creates a performance hit since everything gets loaded as soon as we make the object, even if we dont want to use it.

Lazy Loading - Create the object but don't load the dataset. Load them only when they are required. Basically here we make a proxy object and operate on it.
We load this proxy object with the necessary data from dataset only when they are requested.

Use lazy loading when we are not sure what data we will need at runtime and eager loading when we know what data we want at runtime everytime we load the object.

To save memory, Lazy loading is generally used for one to many and many to many relationships. For one to one, generally Eager is used.


Memorize this :)
OneToMany:    LAZY
ManyToOne:    EAGER
ManyToMany: LAZY
OneToOne:       EAGER
Columns :          EAGER


Example->
public class Organization 
{
 private String employeeID;
 private String name;
 private String address;
 private List<Employees> employees;

 // setters and getters
}

Now when you load a Organization from the database, Hibernate loads its employeeID, name, and address fields for you. But you have two options for employees; to load it together with the rest of the fields (Eager Fetch) or to load it on-demand (Lazy Fetch) when you call the Organization's getListOfEmployees() method.

@ElementCollection(fetch=FetchType.LAZY)   OR @ElementCollection(fetch=FetchType.EAGER) // use either one of the two
@JoinTable(name="EMP_DTLS",joinColumns=@JoinColumn(name="EMP_ID"))

private Collection<Employees> listOfEmployees = new ArrayList<Employees>();
    
public Collection<Employees> getListOfEmployees() {
        return listOfEmployees;
}


Second Level Cache in Hibernate

Caching is a mechanism for storing the loaded objects into cache memory. The advantage of this is, whenever we want to load the same object from the database, instead of hitting the database once again, it loads from the local cache memory, so that the no. of round trips between an application and the database gets reduced.

Caching mechanism increases the performance of the application.

In hibernate we have two levels of caching
First Level Cache [Session Cache]
Second Level Cache [Session Factory Cache or JVM Level Cache]


Whenever we are load any object from the database, hibernate verifies whether that object is available in the local cache memory of that particular session [first level cache], if not, then hibernate verifies whether the object is available in global cache or factory cache [second level cache], if not, then hibernate hits the database and loads the object.

It first stores in the local cache of the session [first level] and then in the global cache [second level cache]

When another session needs to load the same object from the database, then hibernate copies that object from global cache [second level cache] into the local cache of this new session.

Second level cache is from 4 vendors
EHCache Cache from hibernate framework
OSCache from Open Symphony
SwarmCache
TreeCache from JBoss


Steps to enable second level cache in hibernate ->

1) Add provider class in hibernate configuration file.

<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>


2) Add the following in hibernate mapping file.

<cache usage="read-only" />

3) Create ehcache.xml and store in at class path location [place where you have mapping and configuration xml’s] in web application.



Wednesday, October 5, 2016

First Level Cache in Hibernate

Caching is a mechanism for storing the loaded objects into cache memory. The advantage of this is, whenever we want to load the same object from the database, instead of hitting the database once again, it loads from the local cache memory, so that the no. of round trips between an application and the database gets reduced.

Caching mechanism increases the performance of the application.

In hibernate we have two levels of caching
First Level Cache [Session Cache]
Second Level Cache [Session Factory Cache or JVM Level Cache]


By default, for each hibernate application, the first level cache is automatically enabled and we cannot disable it.

First level cache is associated with the session and its scope is limited to one session only.

When we load an object for the first time from the database, the object gets loaded from the database and stored in the cache memory.

If we load the same object once again in the same session, then the object will be loaded from the local cache memory instead of the database.

If we load the same object by opening another session, then again the object will be loaded from the database and stored in the cache memory of this new session.

Example:
1)Session session1 = factory.openSession();
2)Object obj1 = session1.get(Emp.class, new Integer(101));

3)Object obj2 = session1.get(Emp.class, new Integer(101));
4)Object obj3 = session1.get(Emp.class, new Integer(101));

5)session.close();

6)Session session2 = factory.openSession();
7)Object obj4 = session2.get(Emp.class, new Integer(101)); 

In the above example, object will be loaded from the database at line number 2.

But at line number 3 and 4 it will be loaded from the cache.

Again at line number 7 object is loaded from the database since its a new session.

Sunday, October 2, 2016

Dirty loading/checking in Hibernate

Every Hibernate session is cached.

It caches entities read from the database, changes made to entities, as well as added and removed entities; until the session is flushed (ie written to the database).

A session is said to be dirty when some changes have not yet been flushed. This session is flushed before the transaction is committed. It is perfectly normal to have a dirty session.

In simple words: Dirty data is the one which is not yet committed. Similarly, dirty session in hibernate contains modified data which is not yet committed :)

Configuration con = new Configuration();
con.configure("dirty.cfg.xml");
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction trans = session.beginTransaction();

try
{
   Gender gender = (Gender)session.get(Gender.class, new Long(1));
   gender.setName("someName");
   session.getTransaction().commit();
   session.flush();
}
catch(Eception ex)
{
  ex.printStackTrace();
}

Here, we have not called update(), even then object state is written to the database. This is called automatic dirty checking

Hibernate monitors whether any changes are made in the session object and automatically synchronizes them to the database.

session.getTransaction.commit() is mandatory, else correct data will not reflect in the database.

Cascade and Inverse in Hibernate

In case of many-to-many relationship via intermediary table, CASCADE says whether a record will be
created/updated in the child table and INVERSE says whether a record will be created/updated in the
intermediary table

Example:
One student can have multiple phones, so Student class has property for Set of phones.
One Phone can be owned by multiple students, so Phone class has property for Set of Students.

This mapping is maintained in STUD_PHONE table.

So there are three tables -> STUDENT, PHONE and STUD_PHONE (intermediary) table.

Mapping might look like:

<set name="phoneset" table="stud_phone" cascade="save-update" inverse="true">
  <key column="mapping_stud_id">< /key>
  <many-to-many class="com.domain.Phone" column="mapping_phon_id"/>
</set> 

A new student object is created and 2 new phone objects are added to its set.
Now after calling session.save(student_obj) , depending upon CASCADE and INVERSE settings different queries will be fired.

Below are the different combinations->

1) CASCADE IS NONE and INVERSE is false

insert into STUDENT (Name, stud_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)

2) CASCADE is NONE and INVERSE is true

insert into STUDENT (Name, stud_id) values (?, ?)

3) CASCADE is save-update and INVERSE is false

insert into STUDENT (Name, stud_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)
insert into STUD_PHONE (mapping_stud_id, mapping_phon_id) values (?, ?)

4) CASCADE is save-update and INVERSE true

insert into STUDENT (Name, stud_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)
insert into PHONE(phone_num, phone_id) values (?, ?)

Thus only when CASCADE was save-update the records were created in PHONE table, otherwise not.

When INVERSE is false (Student is the owner of relationship) the intermediary table STUD_PHONE was updated.

When INVERSE  is true (Phone is owner of relationship), so even though a new student was created, the intermediary table was not updated.

So in case of relation of two entities, CASCADE affects other entity table and INVERSE  affects intermediary table. So their effect is independent.
Home