What is benefit of using ORM tools?
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
What is Hibernate Framework?
Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.
Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.
What are the important benefits of using Hibernate Framework?
Some of the important benefits of using hibernate framework are:
- Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
- Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
- Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
- Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.
- Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
- Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
- Hibernate cache helps us in getting better performance.
- For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.
Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.
Some of the important advantages of Hibernate framework over JDBC are:
- Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
- Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
- Hibernate implicitly provides transaction management, in fact most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback. JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throwJDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
- Hibernate Query Language (HQL) is more object oriented and close to java programming language. For JDBC, we need to write native sql queries.
- Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
- Hibernate provide option through which we can create database tables too, for JDBC tables must exist in the database.
- Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for connection pool. This is very important feature in enterprise application and completely missing in JDBC API.
- Hibernate supports JPA annotations, so code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
- Programmatic configuration
- XML configuration (hibernate.cfg.xml) -> Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
What is hibernate mapping file?
Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can’t use annotations.
Name some important annotations used for Hibernate mapping?
Hibernate supports JPA annotations and it has some other annotations in org.hibernate.annotations package. Some of the important JPA and hibernate annotations used are:
- javax.persistence.Entity: Used with model classes to specify that they are entity beans.
- javax.persistence.Table: Used with entity beans to define the corresponding table name in database.
- javax.persistence.Access: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.
- javax.persistence.Id: Used to define the primary key in the entity bean.
- javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
- javax.persistence.Column: Used to define the column name in database table.
- javax.persistence.GeneratedValue: Used to define the strategy to be used for generation of primary key. Used in conjunction withjavax.persistence.GenerationType enum.
- javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as OneToMany, ManyToOne and ManyToMany
- org.hibernate.annotations.Cascade: Used to define the cascading between two entity beans, used with mappings. It works in conjunction with org.hibernate.annotations.CascadeType
- javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key. Used with org.hibernate.annotations.GenericGenerator andorg.hibernate.annotations.Parameter
Here are two classes showing usage of these annotations
@Entity
@Table(name = "EMPLOYEE")
@Access(value=AccessType.FIELD)
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "emp_id")
private long id;
@Column(name = "emp_name")
private String name;
@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
//getter setter methods
}
@Entity
@Table(name = "ADDRESS")
@Access(value=AccessType.FIELD)
public class Address {
@Id
@Column(name = "emp_id", unique = true, nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })
private long id;
@Column(name = "address_line1")
private String addressLine1;
@OneToOne
@PrimaryKeyJoinColumn
private Employee employee;
//getter setter methods
}
What are the Core interfaces being 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.
- Session interface
- SessionFactory interface
- Configuration interface
- Transaction interface
- Query and Criteria interface
What role does the Session interface play in Hibernate?
The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. Session is not thread safe so we should not share same session between multiple threads. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
Session interface role:
- Wraps a JDBC connection
- Factory for Transaction
- Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier
What role does the SessionFactory interface play in Hibernate?
Application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work
SessionFactory sessionFactory = configuration.buildSessionFactory();
What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
- Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
- Create session factory from configuration object
- Get one session from this session factory
- Create HQL Query
- Execute query to get list containing Java objects
What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.
What’s the difference between load() and get()?
load()
- Only use the load() method if you are sure that the object exists.
- load() method will throw an exception if the unique id is not found in the database.
- load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.
get()
- If you are not sure that the object exists, then use one of the get() methods.
- get() method will return null if the unique id is not found in the database.
- get() will hit the database immediately.
What is the difference between and merge() and update() ?
update(): if you are sure that the session does not contain an already persistent instance with the same identifier.
merge(): if you want to merge your modifications at any time without consideration of the state of the session.
merge(): if you want to merge your modifications at any time without consideration of the state of the session.
If you want to see the Hibernate generated SQL statements on console, what should we do?
set show_sql property to true in configuration file.
What is the difference between sorted and ordered collection in hibernate?
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.
- As it happens in jvm memory, it can throw Out of Memory error.
Order collection
- Order collection is sorting a collection by specifying the order-by clause in query for sorting this collection when retrieval.
- If your collection is very large, it will be more efficient way to sort it.
What are the Collection types in Hibernate ?
- Bag
- Set
- List
- Array
- Map
What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.
How can Hibernate be configured to access an instance variable directly and not through a setter method?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.
How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true), This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.
What are the types of Hibernate instance states ?
Three types of instance states:
- Transient -The instance is not associated with any persistence context.
- Persistent -The instance is associated with a persistence context. You can update object in database by using session.flush() method.
- Detached -The instance was associated with a persistence context which has been closed – currently not associated. You can reattach detached object to any other session by calling either update() or saveOrUpdate() method on that session.
What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
Sample of Hibernate transaction management?
A org.hibernate.Session is designed to represent a single unit of work (a single atomic piece of work to be performed.
Sample code of handling transaction from hibernate session.
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
How to implement Optimistic locking in Database?
You can implement optimistic locks in your DB table in this way (This is how optimistic locking is done in Hibernate):
- Add integer "version" column to your table.
- Increase value of this column with each update of corresponding row.
- To obtain lock, just read "version" value of row.
- Add "version = obtained_version" condition to where clause of your update statement.
- Verify number of affected rows after update. If no rows were affected - someone has already modified your entry.
Your update should look like
UPDATE mytable SET name = 'Andy', version = 3 WHERE id = 1 and version = 2;
What is hibernate caching? Explain Hibernate first level cache?
As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.
Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However, hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
What is Second Level Cache and QueryCache in Hibernate?
Second level Cache is maintained at SessionFactory level and It improves performance by saving few database round trip. Another worth noting point is that second level cache is available to whole application rather than any particular session.
QueryCache actually stores result of sql query for future calls. Query cache can be used along with second level cache for improved performance. Hibernate support various open source caching solution to implement Query cache e.g. EhCache.
What will happen if we don’t have no-args constructor in Entity bean?
Hibernate uses Reflection API to create instance of Entity beans, usually when you call get() or load() methods. The methodClass.newInstance() is used for this and it requires no-args constructor. So if you won’t have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get HibernateException.
How to implement Joins in Hibernate?
There are various ways to implement joins in hibernate.
- Using associations such as one-to-one, one-to-many etc.
- Using JOIN in the HQL query. There is another form “join fetch” to load associated data simultaneously, no lazy loading.
- We can fire native sql query and use join keyword.
Why we should not make Entity Class final?
Hibernate use proxy classes for lazy loading of data, only when it’s needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.
What is HQL and what are its benefits?
Hibernate Framework comes with a powerful object-oriented query language – Hibernate Query Language (HQL). It’s very similar to SQL except that we use Objects instead of table names, that makes it more close to object oriented programming.
Hibernate query language is case-insensitive except for java class and variable names. So SeLeCT is the same as sELEct is the same as SELECT, but com.journaldev.model.Employee is not same as com.journaldev.model.EMPLOYEE.
The HQL queries are cached but we should avoid it as much as possible, otherwise we will have to take care of associations. However, it’s a better choice than native sql query because of Object-Oriented approach.
Can we execute native sql query in hibernate?
Hibernate provide option to execute native SQL queries through the use of SQLQuery object.
For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching
What is the benefit of native sql query support in hibernate?
Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.
What is Named SQL Query?
Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can have created named queries for both HQL and Native SQL.
Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.
What are the benefits of Named SQL Query?
Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code.
Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries.
Hibernate Named Query is global, means once defined it can be used throughout the application.
Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries.
Hibernate Named Query is global, means once defined it can be used throughout the application.
However, one of the major disadvantage of Named query is that it’s hard to debug, because we need to find out the location where it’s defined.
What is the benefit of Hibernate Criteria API?
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented approach.
Some of the common usage of Criteria API are:
- Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
- Criteria API can be used with ProjectionList to fetch selected columns only.
- Criteria API can be used for join queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and setProjection()
- Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
- Criteria API provides addOrder() method that we can use for ordering the results.
What is Hibernate Proxy and how it helps in lazy loading?
Hibernate uses proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn’t load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object.
What is cascading and what are different types of cascading?
When we have relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it.
Here is a simple example of applying cascading between primary and secondary entities.
import org.hibernate.annotations.Cascade;
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@OneToOne(mappedBy = "employee")
@Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
}
Note that Hibernate CascadeType enum constants are little bit different from JPA javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example.
Commonly used cascading types as defined in CascadeType enum are:
Commonly used cascading types as defined in CascadeType enum are:
- None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in parent affects the child.
- ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
- SAVE_UPDATE: Cascades save and update, available only in hibernate.
- DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
- DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
- LOCK: Corresponds to the Hibernate native LOCK action.
- REPLICATE: Corresponds to the Hibernate native REPLICATE action.
Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
How do you invoke Stored Procedures?
{ ? = call selectAllEmployees() }
What are the benefits does HibernateTemplate provide?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.
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.
How to integrate log4j logging in hibernate application?
Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions. For log4j configuration, we need to follow below steps.
- Add log4j dependencies for maven project, if not maven then add corresponding jar files.
- Create log4j.xml configuration file or log4j.properties file and keep it in the classpath. You can keep file name whatever you want because we will load it in next step.
- For standalone projects, use static block to configure log4j usingDOMConfigurator or PropertyConfigurator. For web applications, you can use ServletContextListener to configure it.
That’s it, our setup is ready. Create org.apache.log4j.Logger instance in the java classes and start logging.
How to use application server JNDI DataSource with Hibernate framework?
For web applications, it’s always best to allow servlet container to manage the connection pool. That’s why we define JNDI resource for DataSource and we can use it in the web application. It’s very easy to use in Hibernate, all we need is to remove all the database specific properties and use below property to provide the JNDI DataSource name.
How to integrate Hibernate and Spring frameworks?
Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. The best part with using Spring is that it provides out-of-box integration support for Hibernate with Spring ORM module. Following steps are required to integrate Spring and Hibernate frameworks together.
- Add hibernate-entitymanager, hibernate-core and spring-orm dependencies.
- Create Model classes and corresponding DAO implementations for database operations. Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration.
- If you are using Hibernate 3, you need to configureorg.springframework.orm.hibernate3.LocalSessionFactoryBeanororg.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBeanin Spring Bean configuration file. For Hibernate 4, there is single class org.springframework.orm.hibernate4.LocalSessionFactoryBean that should be configured.
- Note that we don’t need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using @Transactional annotation.
Which design patterns are used in Hibernate framework?
Some of the design patterns used in Hibernate Framework are:
- Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
- Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
- Proxy Pattern for lazy loading
- Factory pattern in SessionFactory
No comments:
Post a Comment