Prev Next

Hibernate / Hibernate Interview Questions III

Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. How to configure application server JNDI DataSource with Hibernate framework?

For web applications, it is ideal to have the servlet container manage the connection pool. This is achieved by defining JNDI resource for DataSource and use it in the web application. Use the below property to set the JNDI DataSource name.

<property name="hibernate.connection.datasource">java:comp/env/jdbc/MyDBJNDI</property>

2. How to implement Joins in Hibernate?

There are different ways to implement joins in Hibernate.

  • Using associations such as one-to-one, one-to-many,
  • Using JOIN in the HQL query,
  • and by using native sql query with join keyword.
3. Explain the general flow of hibernate.
  • Load configuration file and create instance of configuration class.
  • Using configuration object, create SessionFactory object.
  • From SessionFactory, create session.
  • Create HQL query.
  • Execute HQL query and get the results.
4. What is cascade in Hibernate?

Cascading consists in propagating the Parent entity state transition to one or more Child entities, and it can be used for both unidirectional and bidirectional associations.

5. How to include query hint in Hibernate criteria?

Using Criteria addQueryHint method, we can specify database specific hint.

Criteria addQueryHint(String hint)

6. Difference in positional parameter in JDBC create Query and Hibernate.

In JDBC positional parameter index starts at 1, while it starts at 0 in Hibernate create sql query.

7. Explain Formula annotation in Hibernate.

@Formula annotation is used to calculate a given entity attribute using an SQL query expression. It defines a formula (derived value) which is a SQL fragment that acts as a @Column alternative in most cases. It represents read-only state.

@Entity
@Table(name="area")
public class Area implements Serializable {
	
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name="id")
	private int id;
	
	@Column(name="length")
	private int length;
	
	@Column(name="width") 
	private int width;
	
	@Formula(" length * width ")
	public long area;
	
	...
	}
	

In the example, area property value is calculated using the length and the width properties.

8. How to limit query results in HQL?

Use Query.setMaxResults() to limit the result.

9. How do I order the selected entity when using CriteriaQuery?

You can define an ORDER BY clause with the orderBy method of the CriteriaQuery interface and the asc or desc method of the CriteriaBuilder interface.

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
Root<Book> root = cq.from(Employee.class);
cq.orderBy(cb.asc(root.get(Employee_.firstName)));
 
// Execute query with pagination
List<Employee> emplList = em.createQuery(cq).getResultList();

10. Explain JPA Entity Object Life Cycle.

The life cycle of entity objects consists of four states: New, Managed, Removed and Detached.

When an entity object is initially created its state is New. In this state the object is not yet associated with an EntityManager and has no representation in the database.

An entity object becomes Managed when it is persisted to the database via an EntityManager's persist method, which must be invoked within an active transaction.

A managed entity object can also be retrieved from the database and moved to removed, by using the EntityManager's remove method within an active transaction.

Detached represents entity objects that have been disconnected from the EntityManager.

11. Explain the role of JMX in hibernate.

Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.

12. Does hibernate support polymorphism?

Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.

13. Mention some of the Hibernate Best Practices.
  • Identify natural keys for all entities, and map them.
  • Place each class mapping in its own file.
  • Externalize query strings to make applications more portable.
  • Use bind variables to prevent SQL Injection.
  • Use hand-coded JDBC sparing: Using SQL defeats the entire purpose of using Hibernate. So, use it sparingly, only when it is performance-critical.
  • Prefer lazy fetching for associations. Explicitly disable eager fetching using lazy="false". When join fetching is appropriate to a particular use case, use a query with a left join fetch.
  • Use bidirectional associations: In a large application, almost all associations must be navigable in both directions in queries.
14. Difference between transient and detached objects in hibernate.

Transient objects do not have association with the database and session objects. They are simple objects and not persisted to the database. Once the last reference is lost, that means the object itself is lost. And of course , garbage collected.

The detached object have corresponding entries in the database. These are persistent and not connected to the Session object. These objects have the synchronized data with the database when the session is closed.

15. What happens when a transient mapped object is passed onto a Sessions save?

It has no effect and the transient object retains its state.

16. Explain cascade and inverse properties in one-many mapping.

There is no relationship between cascade and inverse, both serves different purpose.

17. What is inverse = true in hibernate mapping?

It defines which side is the parent or the relationship owner for the two entities. Hence, inverse="true" in a Hibernate mapping shows that this designated class is the relationship owner; while the other class is the child.

18. What is the default fetch type in Hibernate?

The JPA @ManyToOne and @OneToOne annotations are fetched EAGERly by default, while the @OneToMany and @ManyToMany relationships are LAZY by default.

19. What is mappedBy attribute in hibernate?

The attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).

@Entity
public class Movie {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "id", updatable = false, nullable = false)
	private Long id;

	@OneToMany(mappedBy = "movie")
	private List reviews = new ArrayList();

	..
}

b = entityManager.find(Movie.class, 122L);

List reviews = b.getReviews();
Assert.assertEquals(b, reviews.get(0).getMovie());

20. Difference between mappedBy and joinColumn In hibernate.
mappedBy.joinColumn.
The attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. The annotation @JoinColumn indicates that the entity is the owner of the relationship. This means that the corresponding table has a column with a foreign key to the referenced table.
You can access the other table from the class which you have annotated with "mappedBy" (fully bidirectional relationship).You cannot access other table and its one directional.
«
»
Hibernate Caching

Comments & Discussions