Monday, July 4, 2016

Hibernate Interview Questions part1

Hibernate Interview Questions - Part-1
1.What is Hibernate ?
Hibernate is an open source and 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.Hibernate not only takes care of the mapping from Java classes to database tables but also provides data query and retrieval facilities and can significantly reduce development time .Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.

2. Why Should You Use Hibernate ?
Reasons:
Performance :
1.Hibernate employs very agressive, and very intelligent first and second level caching strategy. This is a major factor in acheiving the high scalability.
2..Hibernate spares you a unnecessary database calls and in persistence state it is automated persistence then it still increases the performance.
Productivity, Maintainability, Portability
1.Portability :Hibernates portability accross the relational databases is amazing.It is literally one configuration paramter change. You only have to change the database dialect.
2.Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
3.Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
Cost Effective : Hibernate is free and open source – Cost Effective
Learning curve is short :Since we all have working experience in using Hibernate, and Hibernate is totally object orientated concept, it will shorted our learning curve.
Learning curve is short :Since we all have working experience in using Hibernate, and Hibernate is totally object orientated concept, it will shorted our learning curve.

3.What are the advantages of Hibernate ?
1.Database Independent: Hibernate is database independent and you can use any database of your choice.
2.Caching Framework: There are many caching framework that works with Hibernate. You can use any one in your application to improve the performance of your application.
3.As Hibernate is set of Objects , you don't need to learn SQL language. You can treat TABLE as a Object . In case of JDBC you need to learn SQL.
4.Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.
5.Automatic primary key generation and Object/Relational mapping definition and High Performance
6.In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
7.You can load your objects on start up using lazy=false in case of Hibernate.JDBC Don't have such support.
8.Hibernate Supports automatic versioning of rows but JDBC Not.

4.What are the disadvantages of using hibernate ?
1-For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion(entity to object convertion).
2-Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.
3-Debugging: Sometimes debugging and performance tuning becomes difficult.
4-Slower than JDBC: Hibernate is slower than pure JDBC as it is generating lots of SQL statements in runtime.
5-Not suitable for Batch processing: It advisable to use pure JDBC for batch processing.
6-Composite mapping is complex : If you do not understand it , yes it is complex . But this will not be a disadvantage. We have talked about this here mapping composite keys in hibernate.

5.What are the hibernate features ?
1.Support POJO/POJI model programming .
2.Light weight technology to develop DB s/w independent persistence logic .
3.Allows work with any java,j2ee,framework s/w`s based applications to them interaction with DB s/w.
4.Gives built in transaction management , connection pooling support.
5.Allows to work with 3rd party jdbc connection pool s/w like c3po,proxol and etc....
6.Supports two level caching to reduce network round tips of client APP and DB s/wOne internet explorer browser can share buffer of another browser.
7.Allows to callpl/sql procedures and functions.
8.Gives HQL as database s/w independent query language to perform persistence operations.
9.Allows to work with database specific native SQL to perform persistence operations.
10.Allows object level relationships in the development of persistence logic when tables are there in 11.relationship like one-one,one-many,many-one,many-many etc.
12.Gives special data structures like bag etc... to support object level relationships.
13.Easy to learn and easy to apply.

6.Hibernate Architecture
Hibernate:
1. itself opens connection to database,
2. converts HQL (Hibernate Query Language) statements to database specific statement,
3. receives result set,
4. then performs mapping of these database specific data to Java objects which are directly used by Java application.
Hibernate uses the database specification from Hibernate Properties file. Automatic mapping is performed on the basis of the properties defined in hbm XML file defined for particular Java object.

7. What is the general flow of Hibernate communication with RDBMS ?
General steps:
1 . Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files.
Configuration cfg = new Configuration().configure(CONFIG_FILE_LOCATION);
2 . Create session factory from configuration object
SessionFactory sessionFactory = cfg.buildSessionFactory();
3 . Get one session from this session factory.
Session ses=factory.opensession()
4 . Create HQL query.
Query query = session.createQuery("from EmployeeBean”);
5 . Execute query to get list containing Java objects.
ListfinalList = query.list();

8.what is the difference between jdbc and hibernate ?
1. Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServeretc.In case of JDBC query must be data base specific.
2. As Hibernate is set of Objects , you don?t need to learn SQL language.You can treat TABLE as a Object . Only Java knowledge is need.In case of JDBC you need to learn SQL.
3. Don’t need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.In case of JDBC you need to tune your queries.
4. You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.In case of JDBC you need to implement your java cache .
5. Hibernate supports Query cache and It will provide the statistics about your query and database status.
6. Hibernate Supports automatic versioning of rows but JDBC Not.
7. Development fast in case of Hibernate because you don?t need to write queries
8. No need to create any connection pool in case of Hibernate. You can use c3p0. In case of JDBC you need to write your own connection pool
9. In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.

9. What is ORMsoftwares ?
1. Object-relational mapping software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.
2 . All ORM softwares internally use Jdbc code to perform persistance operation on database table rows
3. ORM softwares are given only to develop persistence logic and they are not suitable to develop other logics like presentation logic,business Logic...etc.
4. ORM softwares are responsible for the synchronization between the object and table row and to develop objects based “O-R Mapping Persistence Logic”.

10. What is ORM ?
The process of mapping java class with database table and class member variables with table columns and making that java class objects representing database table rows by having synchronization between them is called O-R Mapping.Syncronizationbetween object and table row is nothing but modification done in java application will reflect in table row and vice versa.
Hibernate Interview Questions - Part-2

11. What are the ORM levels ?
The ORM levels are:
1 . Pure relational (stored procedure.)
The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.
2 . Light objects mapping (JDBC)
3 . Medium object mapping
4 . Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
12. What is a meant by light object mapping?
The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.
13. What is a meant by medium object mapping?
The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language.
14. What is meant by full object mapping?
Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.
15.What are the Core interfaces are of Hibernate framework?
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
1 . Session interface
2 . SessionFactory interface
3 . Query and Criteria interfaces
16. Explain the role of Session interface in Hibernate.
1 . A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database.
2 . This session object represents persistence context where persistence state hibernate pojo class objects reside representing table rows.
3 . Hibernare session object is the base for the programmer to provide instructions to hibernate s/w to perform persistence operations on the table rows based on the operations performed on the pojo class objects.
4 . Hibernate session object means it is the object of a class that implements org.hibernate.Session interface.
17. Explain the role of SessionFactory interface in Hibernate ?
The SessionFactory is used to create Sessions. Each application is having usually only one SessionFactory. The requests from the servicing client threads obtain the Sessions from the session factory. SessionFactory is thread safe, so that many threads can access it concurrently and requests the sessions.
18. Explain the role of Configurationclass in Hibernate ?
The org.hibernate.cfg.Configuration is used to build an immutable org.hibernate. SessionFactoryobject . Configuration class object activates hibernate software and configure () is the factory method of hibernate.cfg.Configuration class which reads configuration properties from hibernate.cfg.xml file. builtSessionFactory() method uses hibernate.cfg.xml properties of Configuration object Creates jdbc connection pool.
19. Explain the role of Transaction Interface in Hibernate ?
A transaction is associated with a Session and is usually instantiated by a call to session .beginTransaction(). A single session might span multiple transactions since the notion of a session (a conversation between the application and the datastore) is of coarser granularity than the notion of a transaction. However, it is intended that there be at most one uncommitted Transaction associated with a particular Session at any time.
20.What are the important tags of hibernate.cfg.xml?
This configuration file contains details connect to database s/w like driver classes, database url, database username, password and etc..all these details we should pass as the values of hibernate configuration properties . These property names are fixed but values will be passed on the database s/w we use.The following properties are minimum properties of hibernate configuration file for any database.


Hibernate Interview Questions - part-3
21. What is the need for Hibernate xml mapping file?
Any .xml can act as hibernate mapping file. This file name should specify in hibernate configuration file. There is no default name for this file and this file contains various types of O-R mapping configurations like O-R mapping, collection mapping, association mapping, inheritance mapping and etc.
Any Basic O-R mapping means mapping class with table and class member variables with db column names. This file is base file for hibernate s/w to understand O-R mapping configuration related to hibernate persistence classes.
22. What is the use of hibernate dialect property?
This property takes hibernate s/w supplied database s/w specific class name as the value. So this class name will change based on the database s/w and its version that we use in hibernate application. Org.hibernate.dialect.property values helps hibernate s/w to generate and assign intelligent and sensible default values for some hibernate configuration properties(when they are not specified in configuration file) based on the database s/w.
Dialect class names :
Oracle (any version): org.hibernate.dialect.OracleDialect
Oracle 9i : org.hibernate.dialect.Oracle9iDialect
Oracle 10g : org.hibernate.dialect.Oracle10gDialect

23. What are the different states of Hibernate object ?
Hibernate supports the following three object states.Transient: In this state pojo class object doesn’t represent record in the table and object doesn`t contain identify value. It is just ordinary java class object of pojo class and it is not associated with a Hibernate Session.
Persistent: This state object represent table row and maintains synchronization with table row.This state object contains identify value. Programmer uses this state object to perform persistence operations on table rows.The environment in java app that maintains persistence state objects is called persistence content. Detached state, transient state objects reside outside the persistence content.
Detached : This state object contains identify value but doesn`t represent the record because either that associated session is clear or closed.Detached state object doesn’t perform synchronization with record detached state object has represent the record earlier but currently not representing the record that is the reason to have identify value in detached state object .

24. What are the benefits of detached objects?
Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

25. What are the pros and cons of detached objects?
When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.
Cons
" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.
" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.
Pros:
When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.

26. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?
" Hibernate uses the versionproperty, if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. Write your own strategy with Interceptor.isUnsaved().
27. What is the process to configure and choose identity field from the member variables of hibernate pojo class?
scenario1: if pojo class related database table is having one unique key constraint column or one singular primary key constraint column then take that column related member variables in hibernate pojo class and configure that one as singular identity field of pojo class.
Scenario2: if pojo class related database is having composite primary key constraint based on multiple columns then take those multiple columns related member variables of pojo class and configure them as composite identify field of pojo class.
Scenario3: if pojo class related database table contains no constraints, programmer will analyze and guess multiple columns in which duplicative values will not be there then the programmer will take these multiple columns related member variables of pojo class to configure them as composite identify field.
28. What is the Difference between session.update() and session.lock() in Hibernate ?
The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object.
the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session and then "reassociates" them using Session.update() or Session.saveOrUpdate().
Note: Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object.
29. What is the difference between session.update() and session.merge()?
The session.update() update the record only when given object related row is available in the table otherwise updae() fails in record updation(if record is not available).
the session.merge() tries to update the record if the given pojo object related record is available in the database table and if it is not available this method inserts the record by using given pojo class object data. The given instance does not become associated with the session, it remains detached.
30. What is the difference between session.saveOrUpdate() and session.merge()?
session.merge(): if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance the persistent instance is returned
session.saveOrUpdate():The session save or update() takes given pojo class object identify field member variable value as criteria value to check wheather value based record is already available in the table or not if available this method perform update operation otherwise this method perform insert operation.
Note: if you are trying to update objects by using merge() then the given instance does not become associated with the session, it remains detached . if you are trying to update objects by using saveOrUPdate() then the given instance become associated with the session
Hibernate Interview Questions - part-4
31. Difference between session.load() and session.get()?
session.load() performs lazy loading to select the record from the database. session.load() will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object. If no row found , it will throws an ObjectNotFoundException.
session.get() always hit the database and return the real object, an object that represent the database row, not proxy. If no row found , it return null.
32. What is lazy loading Vs Eager Loading ?
are two types of Loading in application. Eager loading and Lazy loading. In eager loading we will fetch all the values from the Persistent storage and cache it. It will make serious performance issues. There we use lazy loading to avoid that scenario.
Sometimes we don't need to load the child table values, In that case we have to us lazy = true in .hbm file. so hibernate will fetch only parent table values. Internally it will load the wrapper class but it does not cache all the values till we perform operation.
33. Explain about version field?
Application level data integrity constants are important if you are making changes to offline information which is again backed by database. Higher level locking or versioning protocol is required to support them. Version field usage comes at this stage but the design and implementation process is left to the developer.
34. Explain about the id field?
This id field corresponds to the surrogate key which is generated by the database. These fields are handled by the id field. Name attribute is used to specify the names of the field and it should correspond to the method name of getid. This also should correspond to long type and the values should be stored I the database in the long column.

35. What are Collection types in Hibernate?
ArrayType,
Constructor: ArrayType(String role, String propertyRef, Class elementClass, boolean isEmbeddedInXML)
BagType,
Constructor: BagType(String role, String propertyRef, boolean isEmbeddedInXML)
CustomCollectionType, A custom type for mapping user-written classes that implement PersistentCollection
Constructor: CustomCollectionType(Class userTypeClass, String role, String foreignKeyPropertyName, boolean isEmbeddedInXML)
IdentifierBagType,
Constructor: IdentifierBagType(String role, String propertyRef, boolean isEmbeddedInXML)
ListType,
Constructor: ListType(String role, String propertyRef, boolean isEmbeddedInXML)
MapType,
Constructor: MapType(String role, String propertyRef, boolean isEmbeddedInXML)
SetType
Constructor: SetType(String role, String propertyRef, boolean isEmbeddedInXML)
36 . What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection
sorted collection :-
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator.
If your collection is not large, it will be more efficient way to sort it.
order collection :-
Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it .
37. Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
38. What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
Common functions are simplified to single method calls.
Sessions are automatically closed.
Exceptions are automatically caught and converted to runtime exceptions.
39 . If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
40. How to prevent concurrent update in Hibernate?
Automatic Versioning: Hibernate can perform automatic optimistic concurrency control for you. It can automatically detect if a concurrent modification occurred during user think time. Check for this at the end of the conversation.


ernate Interview Question Part-5
41.What is the use of filters in hibernate ?
1. Hibernate filters are hibernate 3.x feature that allows the programmer to specify predefined hibernate criteria for the persistence logic of hibernate programming.
2. Filters represents where condition clause related conditions in hibernate mapping file and they are visible for multiple session objects of hibernate application.
3. These filters can be disabled or enabled dynamically at run time on each session object level.
4. A hibernate filter is global named parameterized condition that can be enabled or disabled for a particular hibernate session. When enabled all queries executed using that session object will be executed with the condition of filter.
42.what are the advantages of using HQL ?
1. HQL queries are database independent Queriesso these queries based persistence logic is database independent.
2. HQL queries are “object level queries”so they return hibernate pojo class objects as results.
3. HQL queries and keywords are very much similar to SQL queries of oracle.
4. HQL queries support operators, expressions, conditions , joins,sb queries, aggregate fuctions and etc.
5.HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns
43. what are the disadvantages of using HQL ?
1.HQL queries can’t perform “DDL” operations.
2.HQL queries can’t be used in PL/SQL program
3.HQL queries can’t be used to insert single record into table.
4.An HQL query gives negligible performance degradation because of conversions when compared to SQL.
44.what is difference between getcurrentsession and opensession in hibernate ?
A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs.
If you decide to use manage the Session yourself then go for sf.openSession() , you have to flush() and close() it. It does not flush and close() automatically.
45. what is the difference between select HQL query by using list() and iterate()?
1.list() generates results by selecting all the records through the execution of single select SQL query.(no lazy loading that) by calling getxxx(). the pojo class objects representing results will be initialized with data(records)
2.iterate() select the records from database table by executing multiple SQL select queries (all most one select Query per record and also generates first SQL select query only to retrieve column names.iterate() performs “lazy loading”because it creates and initializes results related hibernate pojo class objects on demand.
3.List () is recommended to use.
4. We can see the above difference between list() and iterate() only when HQL select queries are selecting all the columns of a table.
46. What is the difference between executing SQL select queries in JDBC and SQL select queries in hibernate ?
JDBC code based select queries gives resultset object which is not serializableobject so we cannot send resultset object over the network.
Hibernate based select HQL queries execution gives results in the form of collection framework list data structure since this list data structure is serielizable object by default we can send that object over the network.
Note:All collection frame work data structure are serielizable objects by default.
47. SQL statements execution order in Hibernate .
all entity insertions, in the same order the corresponding objects were saved using Session.save()
all entity updates
all collection deletions
all collection element deletions, updates and insertions
all collection insertions
all entity deletions, in the same order the corresponding objects were deleted using Session.delete()
48.I want to fetch the data from the one database and I want insert that data in to another data base ? how you willdo ?
HQL doesn’t support single row insertion but we can insert multiple records by selecting from one table another table .
Syntax:
insert into Object (id, name) select oo.id, oo.name from OtherObjectoo
Ex:
Query query=session.createQuery("insert into Stock(stock_code, stock_name)"+
"select stock_code, stock_name from backup_stock");
int result =query.executeUpdate();
Insert a stock record from another backup_stock table. This can also called bulk-insert statement.
49.what is native sql in hibernate ?
1. Native SQL queries are underline database s/w specific SQL queries .these queries based persistence logic of hibernate is “database dependent persistence logic” .
2. If programmer is feels certain operation is complex with HQL then it is recommended to use native sql queries.
3. Native SQL queries will be written by database table names and column names.
4. SQL query object represents one native sql query .this is the object of a class that implements org.hibernate.SQLQueryinterface. This interface is sub interface of org.hibernate.Query interface.
5. Native SQL queries programming environment is very useful for the programmer to call “pl/sql procedures and functions of database s/w from hibernate persistence logic.
50.what is CriteriaAPI in hibernate ?
1 . This API is given to develop hibernate persistence logic pure in java statements and without using SQL and HQL queries.
2. Criteria API means working with classes and interfaces of org.hibernate.criterion package classes and interfaces to develop persistence logic.
3 . We can use criteria-api only select operations based persistence logic development and criteria-api is not design to select specific column values of a table it will select all the column values.
4 . While developing the criteria –api based persistence logic pojo classes, member variable names will be utilized.Criteria-api based persistence logic is “database independent”persistence logic.

ate Interview Questions - Part-6

51.What is Hibernate proxy?
In hibernate proxies are placeholder that are generated at runtime. Whenever hibernate returns an instance of any entity class, it checks weather it returns a proxy object to avoid the database hit.
In hibernate proxies are triggers the loading of real object when it just accessed at very first time.
When we use session.load(…….) to get the resultset of any entity with the help of identifier an by calling the property other than identifier, the proxy is initialized.
52. What does session.refresh() do ?
Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances. For example
1 . where a database trigger alters the object state upon insert or update
2 . after executing direct SQL (eg. a mass update) in the same session
3 . after inserting a Blob or Clob
53. Define cascade and inverse Hibernate ?
Inverse : An inverse keyword has the boolean value "true/false". Default value of this keyword is 'false' it means the parent class is responsible for saving/updating the child and it's relationship. And when the keyword inverse is set to the 'true' it means an associatedsubclass is responsible for saving/updating itself.
Cascade :The “Cascade” keyword is often appear on the collection mapping to manage the state of the collection automatically. Cascade has the various options "all ", " save | update | delete | merge " that may be used with either of the single option or may be used with the multiple options. Cascade decides the same operation done on the parent object is done on the associated object at the same time.
54. how are joins handled using hibernate ?
1 . Joins are given to get common or uncommon data or records from 2 database tables by making them as leftside table for join.
2 . To work with SQL joins , the database tables (2 tables) need not be in relationship but in HQL joins the 2 database tables and its related hibernate pojo classes must be there in relationship.
3 . HQL joins will be return on hibernate pojo classes that are acting on 2 hibernate pojo classes that are acting as parent, child pojo classes.
55. how to create primary key using hibernate?
The id element describes the primary key for the persistent class and the generator class automatically generate the primary key for id
<id name="id" column="id" type="long">
<generator class="increment"/>
56. What is the use of addScalar method in hibernate ?
Creates a new instance of SQLQuery for the given SQL query string and the entities returned by the query are detached.
Query query = session.createSQLQuery(sql).addScalar("stdErr",Hibernate.DOUBLE).
addScalar("mean",Hibernate.DOUBLE);
57. What is first level cache in hibernate?
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
58. What is Second-level cache in hibernate?
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded inthe cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works.Here we can use query level cache also. Later we will discuss about it.
59. What is the main difference between Entity Beans and Hibernate ?
Entity beans are to be implemented by containers, classes, descriptors. Hibernate is just a tool that quickly persist the object tree to a class hierarchy in a database and without using a single SQL statement. The inheritance and polymorphism is quite simply implemented in hibernate which is out of the box of EJB and a big drawback.
60 . How to Execute Stored procedure in Hibernate ?
In Hibernate, there are three approaches to call a database store procedure.
1 . You can use createSQLQuery() to call a store procedure directly.
Query query = session.createSQLQuery(
"CALL GetStocks(:stockCode)")
.addEntity(Stock.class)
.setParameter("stockCode", "7277");
2. Declare your store procedure inside the ©NamedNativeQueries annotation

@NamedNativeQueries({
@NamedNativeQuery(
name = "callStockStoreProcedure",
query = "CALL GetStocks(:stockCode)",
resultClass = Stock.class )
})
3. Declare your store procedure inside the “sql-query” tag.
<sql-query name="callStockStoreProcedure">
<return alias="stock" class="com.mkyong.common.Stock"/>
</sql-query>



1 comment: