Wednesday, January 6, 2016

What is DetachedCriteria in Hibernate ?

Ref:- https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/criterion/DetachedCriteria.html

public class DetachedCriteria
extends Object
implements CriteriaSpecification, Serializable
Some applications need to create criteria queries in "detached mode", where the Hibernate session is not available. This class may be instantiated anywhere, and then a Criteria may be obtained by passing a session to getExecutableCriteria(). All methods have the same semantics and behavior as the corresponding methods of the Criteria interface.

Monday, January 4, 2016

What is lazy loading?

Lazy loading is a technique in which objects are loaded on demand basis. Since Hibernate 3, lazy loading is by default, enabled so that child objects are not loaded when parent is loaded.

What is the difference between save() and persist() methods of session object?

session.save saves the object and returns the id of the instance whereas persist do not return anything after saving the instance.

Is SessionFactory a thread-safe object?

Yes, SessionFactory is a thread-safe and can be accessed by multiple threads simultaneously.

But Session is not thread-safe.

What’s difference between managed associations and hibernate associations?

Ref:- http://career.guru99.com/hibernate-interview-questions/

Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.

What’s general hibernate flow using RDBMS?

Ref:- http://career.guru99.com/hibernate-interview-questions/

General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.

How can we map the classes as immutable?

Ref:- http://career.guru99.com/hibernate-interview-questions/

If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false

What the three inheritance models are of hibernate?

Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class

What’s the use of session.lock() in hibernate?

Ref:- http://career.guru99.com/hibernate-interview-questions/

session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.

What’s the difference between load() and get() method in hibernate?

Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.

What is meant by a Named SQL Query in hibernate and how it’s used?

Ref:- http://career.guru99.com/hibernate-interview-questions/

Named SQL queries are those queries which are defined in mapping file and are called as required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:
[xml]
<sql-query name = “studentdetails”>
<return alias=”std”/>
SELECT std.STUDENT_ID AS {std.STUDENT_ID},
std.STUDENT_DISCIPLINE AS {std.discipline},
FROM Student std WHERE std.NAME LIKE :name
</sql-query>
[/xml]
Then this query can be called as follows:
[java]
List students = session.getNamedQuery(&amp;quot;studentdetails&amp;quot;)
.setString(&amp;quot;TomBrady&amp;quot;, name)
.setMaxResults(50)
.list();
[/java]

What different fetching strategies are of hibernate?

Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching

How can we reattach any detached objects in Hibernate?

Ref:- http://career.guru99.com/hibernate-interview-questions/

Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.

What are the two mapping associations used in hibernate?

http://career.guru99.com/hibernate-interview-questions/

In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association

What is the default cache service of hibernate?

http://career.guru99.com/hibernate-interview-questions/

Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.

How can we reduce database write action times in Hibernate?

Ref:- http://career.guru99.com/hibernate-interview-questions/

Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.

How can we get hibernate statistics?

Ref:- http://career.guru99.com/hibernate-interview-questions/

We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()

What’s the difference between session.save() and session.saveOrUpdate() methods in hibernate?

Ref:- http://career.guru99.com/hibernate-interview-questions/

Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.

How can we invoke stored procedures in hibernate?

Ref:- http://career.guru99.com/hibernate-interview-questions/

In hibernate we can execute stored procedures using code as below:
[xml]
<sql-query name=”getStudents” callable=”true”>
<return alias=”st” class=”Student”>
<return-property name=”std_id” column=”STD_ID”/>
<return-property name=”s_name” column=”STD_NAME”/>
<return-property name=”s_dept” column=”STD_DEPARTMENT”/>
{ ? = call selectStudents() }
</return>
</sql-query>
[/xml]

Hibernate – Cascade example (save, update, delete and delete-orphan)

Ref:- http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/

The “Cascade” keyword is often appear on the collection mapping to manage the state of the collection automatically. In this tutorials, this one-to-many example will be used to demonstrate the cascade effect.

Cascade save / update example

In this example, if a ‘Stock’ is saved, all its referenced ‘stockDailyRecords’ should be saved into database as well.

1. No save-update cascade

In previous section, if you want to save the ‘Stock’ and its referenced ‘StockDailyRecord’ into database, you need to save both individually.
Stock stock = new Stock();
StockDailyRecord stockDailyRecords = new StockDailyRecord();
//set the stock and stockDailyRecords  data

stockDailyRecords.setStock(stock);        
stock.getStockDailyRecords().add(stockDailyRecords);

session.save(stock);
session.save(stockDailyRecords);
Output
Hibernate: 
    insert into mkyong.stock (STOCK_CODE, STOCK_NAME) 
    values (?, ?)

Hibernate: 
    insert into mkyong.stock_daily_record
    (STOCK_ID, PRICE_OPEN, PRICE_CLOSE, PRICE_CHANGE, VOLUME, DATE) 
    values (?, ?, ?, ?, ?, ?)

2. With save-update cascade

The cascade=”save-update” is declared in ‘stockDailyRecords’ to enable the save-update cascade effect.
<!-- Stock.hbm.xml -->
<set name="stockDailyRecords" cascade="save-update" table="stock_daily_record"...>
      <key>
            <column name="STOCK_ID" not-null="true" />
      </key>
      <one-to-many class="com.mkyong.common.StockDailyRecord" />
</set>
Stock stock = new Stock();
StockDailyRecord stockDailyRecords = new StockDailyRecord();
//set the stock and stockDailyRecords  data

stockDailyRecords.setStock(stock);        
stock.getStockDailyRecords().add(stockDailyRecords);

session.save(stock);
Output
Hibernate: 
    insert into mkyong.stock (STOCK_CODE, STOCK_NAME) 
    values (?, ?)

Hibernate: 
    insert into mkyong.stock_daily_record
    (STOCK_ID, PRICE_OPEN, PRICE_CLOSE, PRICE_CHANGE, VOLUME, DATE) 
    values (?, ?, ?, ?, ?, ?)
The code session.save(stockDailyRecords); is no longer required, when you save the ‘Stock’, it will “cascade” the save operation to it’s referenced ‘stockDailyRecords’ and save both into database automatically.

Cascade delete example

In this example, if a ‘Stock’ is deleted, all its referenced ‘stockDailyRecords’ should be deleted from database as well.

1. No delete cascade

You need to loop all the ‘stockDailyRecords’ and delete it one by one.
Query q = session.createQuery("from Stock where stockCode = :stockCode ");
q.setParameter("stockCode", "4715");
Stock stock = (Stock)q.list().get(0);
    
for (StockDailyRecord sdr : stock.getStockDailyRecords()){
         session.delete(sdr);
}
 session.delete(stock);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?

Hibernate: 
    delete from mkyong.stock 
    where STOCK_ID=?

2. With delete cascade

The cascade=”delete” is declared in ‘stockDailyRecords’ to enable the delete cascade effect. When you delete the ‘Stock’, all its reference ‘stockDailyRecords’ will be deleted automatically.
<!-- Stock.hbm.xml -->
<set name="stockDailyRecords" cascade="delete" table="stock_daily_record" ...>
      <key>
            <column name="STOCK_ID" not-null="true" />
      </key>
      <one-to-many class="com.mkyong.common.StockDailyRecord" />
</set>
Query q = session.createQuery("from Stock where stockCode = :stockCode ");
q.setParameter("stockCode", "4715");
Stock stock = (Stock)q.list().get(0);
session.delete(stock);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?

Hibernate: 
    delete from mkyong.stock 
    where STOCK_ID=?

Cascade delete-orphan example

In above cascade delete option, if you delete a Stock , all its referenced ‘stockDailyRecords’ will be deleted from database as well. How about if you just want to delete two referenced ‘stockDailyRecords’ records? This is called orphan delete, see example…

1. No delete-orphan cascade

You need to delete the ‘stockDailyRecords’ one by one.
StockDailyRecord sdr1 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                            new Integer(56));
StockDailyRecord sdr2 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                            new Integer(57));

session.delete(sdr1);
session.delete(sdr2);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?

2. With delete-orphan cascade

The cascade=”delete-orphan” is declared in ‘stockDailyRecords’ to enable the delete orphan cascade effect. When you save or update the Stock, it will remove those ‘stockDailyRecords’ which already mark as removed.
<!-- Stock.hbm.xml -->
<set name="stockDailyRecords" cascade="delete-orphan" table="stock_daily_record" >
      <key>
            <column name="STOCK_ID" not-null="true" />
      </key>
      <one-to-many class="com.mkyong.common.StockDailyRecord" />
</set>
StockDailyRecord sdr1 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                       new Integer(56));
StockDailyRecord sdr2 = (StockDailyRecord)session.get(StockDailyRecord.class, 
                                       new Integer(57));

Stock stock = (Stock)session.get(Stock.class, new Integer(2));
stock.getStockDailyRecords().remove(sdr1);
stock.getStockDailyRecords().remove(sdr2);
  
session.saveOrUpdate(stock);
Output
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
Hibernate: 
    delete from mkyong.stock_daily_record 
    where DAILY_RECORD_ID=?
In short, delete-orphan allow parent table to delete few records (delete orphan) in its child table.

How to enable cascade ?

The cascade is supported in both XML mapping file and annotation.

1. XML mapping file

In XML mapping file, declared the cascade keyword in your relationship variable.
<!-- Stock.hbm.xml -->
<set name="stockDailyRecords" cascade="save-update, delete" 
        table="stock_daily_record" ...>
      <key>
            <column name="STOCK_ID" not-null="true" />
      </key>
      <one-to-many class="com.mkyong.common.StockDailyRecord" />
</set>

2. Annotation

In annotation, declared the CascadeType.SAVE_UPDATE (save, update) and CascadeType.REMOVE (delete) in @Cascade annotation.
        //Stock.java
        @OneToMany(mappedBy = "stock")
        @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
 public Set<StockDailyRecord> getStockDailyRecords() {
  return this.stockDailyRecords;
 }

inverse vs cascade

Both are totally different notions, see the differential here.

Conclusion

Cascade is a very convenient feature to manage the state of the other side automatically. However this feature come with a price, if you do not use it wisely (update or delete), it will generate many unnecessary cascade effects (cascade update) to slow down your performance, or delete (cascade delete) some data you didn’t expected.