Hibernate / Hibernate interview questions II
Hibernate provides a handful of methods that store or update the object into the database. They are,
- save().
- update().
- saveOrUpdate().
- saveOrUpdateCopy().
- merge().
- and persist().
The purpose of these methods is as follows.
save method persists an entity. It assigns an identifier if entity doesn't exist in the database. If exists, save method performs an update. In both cases save method returns the generated ID of the entity.
Update method updates the existing object using identifier. If the identifier does not exist, it throws an exception.
saveOrUpdate method checks if the object is transient (i.e. it has no identifier) and if so it performs save that will make it persistent by generating an identifier and assigning it to session. If the object has an identifier already, it performs update().
saveOrUpdateCopy method is deprecated and no longer in use. Use merge method instead.
merge method is used to update the object to the database in any state of the session.
persist method makes a transient object persistent. However, it doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, thats why the method does not return generated ID.
Sometimes, it is required to re-load an object and its collections at a time when the application database is modified with some external application or database triggers and thus corresponding hibernate entity in your becomes out of sync with its database representation.
In this case, one can use session.refresh() method to re-populate the entity with latest data available in database.
session.lock() method is used to reattach an object which has been detached earlier.
Using session.lock() does not check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.
Sorted collection is the way of sorting a collection by leveraging the sorting features provided by the Java collections framework. This sorting uses Java comparator and it takes place in the memory of JVM in which Hibernate is running, once the data being read from database.
Ordered collection refers to the sorting of a collection by specifying the order-by clause when retrieval.
Ordered collection is preferred for larger data set whereas if the collection is considerably small, sorted collection is preferred. Smaller the collection lesser impact on the JVM memory.
The EmbeddedId and IdClass annotations are used to denote composite primary keys.
The following are some of the rules that is applied for composite primary keys.
- The primary key class must be public and must have a public no-arg constructor.
- The primary key class must be serializable.
- The primary key class must define equals and hashCode methods.
Using EmbeddedId.
@Embeddable public class EntityKey implements Serializable { protected Integer compositeKey1; protected Integer compositeKey2; public EntityKey() {} public EntityKey(Integer key1, Integer key2) { this.compositeKey1 = key1; this.compositeKey2 = key2; } // equals, hashCode } @Entity public class HibernateEntity implements Serializable { @EmbeddedId private EntityKey primaryKey; private String description; //... }
Using IdClass.
public class EntityKey implements Serializable { protected Integer compositeKey1; protected Integer compositeKey2; public EntityKey() {} public EntityKey(Integer key1, Integer key2) { this.compositeKey1 = key1; this.compositeKey2 = key2; } // equals, hashCode } @Entity @IdClass(EntityKey.class) public class HibernateEntity implements Serializable { @Id private Integer compositeKey1; @Id private Integer compositeKey2; private String description; //... }
- Domain Model Pattern - An object model of the domain that incorporates both behavior and data,
- Data Access Object (DAO) Design Pattern,
- Abstract Factory,
- Data Mapper,
- Proxy for lazy loading,
- Object-Relational Mapping (ORM),
- Query Object for Criterion API,
- and facade.
Hibernate provides an Object oriented view of the database by mapping the various classes to the database tables. This facilitates Object oriented thinking rather than relational and hence increases productivity.
Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. Since this session object belongs to the hibernate context, we don't need to close it. Once the session factory is closed, this session object gets closed.To enable this feature, we need to configure it in hibernate configuration file.
<property name="hibernate.current_session_context_class">thread</property>
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.
JPA leverages metadata from persistence.xml while Hibernate API uses hibernate.cfg.xml.
The latest version of hibernate 5.2 released on August 2016.
The persistent class cannot be final.
You must have a default no-argument constructor for your persistent classes.
getXXX() (getters) and setXXX(mutator/setter) methods for all your persistable instance variables should be available.
You should implement the equals() and hashCode() methods based on your business key.
It is recommended to implement the Serializable interface.
There are several ways to implement joins in hibernate.
- By using associations such as one-to-one, one-to-many mappings.
- Using JOIN in the HQL query. There is another form 'join fetch' to load associated data simultaneously and it is no lazy loading.
- execute native sql query and use join keyword.
A Component mapping is a mapping for a class having a reference to another class as a member variable.
No. In Hibernate, collection mapping can only be performed with One-to-Many and Many-to-Many relationship.
Configuring the entity class property mutable to false (mutable="false"), class becomes an immutable class. By default, it is mutable="true".
Yes. In Hibernate we can switch to different database by changing appropriate SQL Dialect configuration.
Hibernate OGM provides Java Persistence (JPA) support for NoSQL solutions. It reuses Hibernate ORM's engine however it persists entities into a NoSQL datastore like mongoDB rather than a relational database like mySQL, Oracle etc.
Hibernate will fail to instantiate the entity bean and issues HibernateException.
Hibernate uses Reflection API Class.newInstance() to create instance of Entity beans that requires requires no-args constructor, usually when you call get() or load() methods. The instance of the entity bean cannot be created when there is no no-arg (default) constructor.
For web applications, it is always a good practice to allow servlet container to manage the connection pool. This is the reason we define JNDI resource for DataSource and we look it up in the web application. Hibernate need to used the below property to configure and lookup by JNDI DataSource name.
<property name="hibernate.connection.datasource">java:comp/env/jdbc/myTestDB</property>
Using session.merge() method. Objects that are detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method.
In Attribute oriented programming, one can add Meta data or attributes in the source code to signify the code. For hibernate, attribute oriented programming is enabled by an engine called XDoclet.
Yes, hibernate provides complete support to polymorphism. Polymorphism queries and associations are supported at all the mapping strategies of hibernate.
Derived properties are those which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.
transient annotation is used to denote such properties.
Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.
All the mapping between entity class and database table, properties and columns, Java types and SQL types etc is referred as ORM metadata.
Managed associations corresponds to the container managed persistence and it is bi-directional while hibernate associations are unidirectional.
HibernateTemplate is a helper utility class that provides different methods for querying/retrieving data from the database. It also converts checked Hibernate Exceptions to unchecked DataAccessExceptions.
It manages the session and transactions by automatically opening and closing when you execute the code.
Following are the four ORM levels in hibernate.
- Pure Relational.
- Light Object Mapping.
- Medium Object Mapping.
- and Full Object Mapping.
The entire application along with the user interface (UI) is designed on the basis of relational model and SQL-based relational operations.
The entities are represented as Java classes that are mapped manually to the relational tables. The code is abstracted/hidden from the business logic using specific design patterns.
This approach is desirable for applications with less number of entities, or applications with common, metadata-driven data models.
Version property in hibernate helps to identify whether an object is in transient state or in detached state.
The application is built on the basis of an object model. The SQL code is generated at build time. The associations between objects are supported by the persistence mechanism and queries are specified using an object-oriented expression language.
This is best suited for medium-sized applications with some complex transactions.
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.
When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are referred as Extension interfaces.
Create a database table with column having data type as blob ( or equivalent) and in the HBM configuration file, specify the column type as binary.
JMX API, a standard API manages applications and components in hibernate. JMX provides tools for development of efficient and robust distributed, web based solutions.
Object identification can be done in hibernate in following 3 ways.
- Using Object Identity: Using == operator.
- Using Object Equality: Using equals() method.
- Using database identity: Relational database objects can be identified if they represent same row.
Version property is used in hibernate to determine whether an object is in transient state or in detached state.
Consider a Parent table associated with a Child table. When we load the Parent table, In lazy association, the Child relationship is loaded when it is needed. This is the default configuration in Hibernate.
SchemaValidator tool is used to verify if the mapping configured matches the existing database structure.
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.
A CRUD operation deals with creating, retriving , updating and deleting from the table.
SQL queries that gets a list of scalars (values) is referred as scalar queries.
sess.createSQLQuery("SELECT * FROM Emp").list();
These will return a List of Object arrays (Object[]) with scalar values for each column in the Emp table.
Entity query gets entity objects from a native sql query using addEntity().
sess.createSQLQuery("SELECT * FROM Emp").addEntity(Employee.class);
Session.createCriteria creates a new Criteria instance, for the given entity class, or a superclass of an entity class.
Java classes objects or instances that will be stored in database tables are called persistent classes in Hibernate.
Batch processing helps performing data load operations involving high volume transactions that minimize the time required and also is memory efficient.
Yes. It is.
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.
Using Automatic Versioning Hibernate can perform automatic optimistic concurrency control. It can automatically detect if a concurrent modification occurred during user think time.
HQL queries cannot perform DDL operations.
HQL queries cannot insert single record into table.
An HQL query gives negligible performance degradation because of conversions when compared to SQL.
HQL queries cannot call PL/SQL program.
HQL queries are database independent.
HQL queries are object level queries and it returns hibernate pojo class objects as results.
HQL queries and keywords are very much similar to SQL queries.
HQL queries support operators, expressions, conditions ,joins, sub queries, aggregate functions etc.
Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you,
- before query executions,
- when a transaction is committed.
flush(): Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.it will update or insert into your tables in the running transaction, but it may not commit those changes.
Commit(): Commit will make the database commit.When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer.So You should commit but it also ends the unit of work.
Hibernate named queries lets developer to put all HQL into the XML mapping file or via annotation so that it is easy to maintain and separated from Java code.
The named query is supported in both HQL or native SQL.
The queries can be retrieved using the query names as shown below.
Query query = session.getNamedQuery("HQL_GET_ALL_EMPLOYEE");
CDATA stands for Character Data and it means that the data in between these strings includes data that could be interpreted as XML markup, but should not be.
Hibernate is database agnostic and it can work with different databases. However, databases have native SQL variations, and its own set of SQL standard implementations. Therefore at some point hibernate has to use database specific SQL. Hibernate uses "dialect" configuration to know which database you are using so that it can switch to the database specific SQL generator code wherever/whenever necessary.
The proxy attribute facilitates the 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.
Hibernate interceptor is a powerful feature that allows application to react to certain events that occur inside Hibernate. This allows for the implementation of generic functionality and the extension of Hibernate functionality.
Hibernate Disjunction adds multiple restrictions/coditions to the HQL query joined by "OR" condition.
Hibernate Conjunction adds multiple restrictions/coditions to the HQL query joined by "AND" condition.
addScalar method specifies the result of the query to return objects for individual named columns, rather than entities.
Query myQuery = new SqlQuery("Select name as nm from employee"); myQuery.addScalar("nm", String);
A hibernate Session is similar to establishing a JDBC connection to the database. When a Session is created in Hibernate, it open up a JDBC connection to the database. When the session is clouded, its close the JDBC connection. Similarly, when transaction is started on hibernate session, it actually start a JDBC transaction.
Hibernate Criteria Transformer is an interface that transforms any result of Hibernate Criteria element.
Criteria criteria = session.createCriteria(Employee.class); criteria.add(Restrictions.eq("name", "Jeff")); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Use named parameters in queries to avoid sql injection.
Query query= sessionFactory.getCurrentSession().createQuery("from UserInfo where userName=:userName"); query.setParameter("username", userName);
Enable logging for the categories, org.hibernate.SQL and org.hibernate.type.
# logs SQL statements log4j.logger.org.hibernate.SQL=debug # Logs JDBC parameters passed to a query log4j.logger.org.hibernate.type=trace
The property 'org.hibernate.SQL' is equivalent to hibernate.show_sql=true, and the second prints the bound parameters.
Hibernate provides dirty checking feature that reduces database write times. Dirty checking feature updates only those fields which require a change while keeps others unchanged.