JavaSpartans
Java J2ee Struts Hibernate Spring Interview Questions Java J2ee Struts Hibernate Spring Interview Questions
1 2 3 4    Next

1. What is Hibernate ?

Hibernate is a tool which hides the data accessing logic. Using Hibernate without writing a single SQL Query we can access the data from the database. Even if you have no knowledge of SQL, you can access data.
If the project size is very large, writing DAO's needs an expert level JDBC Programmer who can write minimal code with standards. But with out knowing all these we can use hibernate which will generate standard code to access data.
Hibernate is an ORM tool. Object Relational Mapping tool. We can store an employee object directly into the database using setters and getters.
Hibernate is a complete alternative for JDBC. If you want you can write SQL queries on your own but hibernate's main purpose is it will write SQL queries at background for you.
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.


2. What do you mean by Named SQL query in hibernate ?

Named SQL queries are defined in the hibernate mapping xml document

and called wherever required.

Example :
<sql-query name = "empdetails">
   <return alias="emp" class="com.test.Employee"/>
      SELECT emp.EMP_ID AS {emp.empid},
                 emp.EMP_ADDRESS AS {emp.address},
                 emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name

</sql-query>
How to Invoke Named Query from Java code:
List people = session.getNamedQuery("empdetails").setString("TomBrady",name).setMaxResults(50).list();



3. Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

  • Improved productivity
    • High-level object-oriented API
    • Less Java code to write
    • No SQL to write
  • Improved performance
    • Sophisticated caching
    • Lazy loading
    • Eager loading
  • Improved maintainability
    • A lot less code to write
  • Improved portability
    • ORM framework generates database-specific SQL for you


4. How do you invoke Stored Procedures from Hibernate?

Just use callable="true" in named sql query.


<hibernate-mapping> 
  <sql-query name="selectPaymentMaster_SP" callable="true">
<return alias="paymentMaster" class="com.gateway.payment.model.PaymentMaster">

</return>
{ call OC_PAYMENT_METHOD_SEL(?,  :-P     aymentTypeCode, :callingAPI) }
  </sql-query>
</hibernate-mapping>

code to invoke stored procedure

public List<PaymentMaster> search(PaymentMasterSearch paymentMasterSearchValue) throws PaymentException {
        LOGGER.debug(" $$$---Start of search  method in the  PaymentMasterService:");
        Session sessionObj;
        List<PaymentMaster> paymentMasterlist;
        try {
            if (paymentMasterSearchValue != null) {
                sessionObj = HibernateUtil.currentSession();
 
                String keyWord = paymentMasterSearchValue.getSearchKeyWord();
                paymentMasterlist = sessionObj.getNamedQuery("selectPaymentMaster_SP")
                        .setParameter("paymentTypeCode", keyWord)
                        .setParameter("callingAPI", "OC25")
                        .list();
                HibernateUtil.closeSession();
 
            } else {
                LOGGER
                        .debug(" $$$--Invalid payment master Search data.");
                throw new PaymentException("Invalid payment master Search data.");
            }
 
        } catch (Exception ex) {
            LOGGER.error("Could not find a payment master Record." , ex);
            throw new PaymentException("Error in  Proccessing the search method.",ex);
        }
        return paymentMasterlist;
    }
  


5. Can you explain about Cursor ?

A cursor is a pointer used to fetch rows from a result set. One can think of a cursor as a data structure that describes the results returned from a SQL SELECT statement. One of the variables in this structure is a pointer to the next record to be fetched from the query results.

Note that if you do repetitive stuff inside a loop and you fail to close your cursors, you would soon run into the ORA-01000: maximum number of open cursors exceeded error.


6. What is a Union in SQL. Give a real-time example ?

Set operations allow the results of multiple queries to be combined into a single result set.
Set operators include UNION, INTERSECT, and EXCEPT.
The SQL UNION operator is used to combine the result sets of 2 or more SELECT statements.
It removes duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION must have the same number of fields or columns in the result sets with similar data types.


7. How do you configure DataSource in Struts ? How do you implement Connection Poooling in Struts ?

Connection Pooling in Struts :

In struts-config.xml file data sources tag is there? you can configure connection pool from that xml file and you can create the connection as below.

<struts-config>
<data-sources>
<data-source type="org.apache.commons.dbcp.BasicDataSource">
<set-property property="driverClassName" value="com.mysql.jdbc.Driver" />
<set-property property="url" value="jdbc:mysql://localhost/DBNAME" />
<set-property property="username" value="" /> 
<set-property property="password" value="abcdefgh" />
<set-property property="maxActive" value="20" />
<set-property property="maxWait" value="5000" />
<set-property property="defaultAutoCommit" value="false" />
<set-property property="defaultReadOnly"   value="false" />  
data-source>
data-sources>
...//Here Other Struts Configuration Tags...
struts-config >

In the above file the default values comes with this file was maxActive 20.
You can set the values here as per your network traffic on your server?
Here totally 20 connection objects will be active in the pool and 5000 (5 seconds ) will be the time to wait for a connection object. You can set number of maxIdle connections also.

CODE : in your Action Class execute method or any other class you can create the connection object like this.
//Just declare the data source and connection objects;
javax.sql.DataSource dataSource = null;
java.sql.Connection myConnection = null;

//Just by using the following 2 lines of Code you can create a connection //object from the data source by using the concept of connection pooling.

dataSource = getDataSource(request);
myConnection = dataSource.getConnection();

You can also refer to EJB Instance Pooling...

How do you configure data source in Tomcat ?
How do you configure data source in WebLogic ?
How do you configure data source in JBoss ?
How do you configure data source in WebSphere ?


8. What is the advantage of Hibernate over jdbc ?

Its a ORM framework
You can think in terms of oops concepts and persist object to a database table row.

It reduces repeated boiler plate code.

It simplifies complex relation ships among tables.

Hibernate provides a caching mechanism, which helps reduce the number of hits, as much as possible, that your application makes to the database server. This will have a considerable effect regarding the performance of your application. There is no such caching mechanism available in JDBC.

Database Independent

Hibernate's code is database independent because you do not need to change the HQL queries (with a few exceptions) when you change databases like MySQL, Oracle, etc. Hence, it is easy to migrate to a new database. It is achieved by using a friendly dialect to communicate with the database. The database can be specified using a dialect in the Hibernate configuration XML as follows.

<property name="dialect">org.hibernate.dialect.MySQL</property>

Below query helps to undertand this.

SQL TOP, LIMIT and ROWNUM Examples

SELECT TOP 3 * FROM Customers; (for SQL Server/MS Access):
SELECT * FROM Customers LIMIT 3; (for MySQL):
SELECT * FROM Customers WHERE ROWNUM <= 3; (for Oracle):

If you deal with query like above then you need to face troubles in switching databases.


9. What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

  • dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
  • dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.


10. What is SQL?

SQL is a domain-specific language used in programming and designed for managing data held in a relational database management system, or for stream processing in a relational data stream management system. It is particularly useful in handling structured data, i.e. data incorporating relations among entities and variables.


Java J2ee Struts Hibernate Spring Interview Questions
1 2 3 4    Next
Menu - javaspartans.com - Java J2ee Struts Spring Hibernate Interview Questions
Hostens.com - A home for your website
Ads By Google