Hibernate Interview Questions Series Part 5

This is the Series four of Hibernate Interview Questions

41. What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
42. What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object, for example, when an object is loaded, saved, or deleted. Hibernate applications don’t need to implement these callbacks, but they’re useful for implementing certain kinds of generic functionality.
43. What are the types of Hibernate instance states?
Three types of instance states:
• Transient: This instance is never been associated with any one of the persistence process. This does not have persistent identity like primary key value.
• Persistent: A persistent context is made to associate with the current instance. It has persistent identity like primary key value and a corresponding row of a table in the data base. Hibernate guarantees the persistent identity is equivalent to the java Identity [object], for a particular persistence context
• Detatched: This instance association with a persistence context is only once and the context was closed or serialized to another process. The persistent identity is retained and it can be a corresponding row in a database.

44. What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0:-

Hibernate EJB 3.0
Session–Cache or collection of loaded objects relating to a single unit of workPersistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Oriented ProgrammingJava 5.0 Annotations used to support Attribute Oriented Programming
Defines HQL for expressing queries to the databaseDefines EJB QL for expressing queries
Supports Entity Relationships through mapping files and annotations in JavaDoc
Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API
Provides and Entity Manager Interface for managing CRUD operations for an Entity
Provides callback support through lifecycle, interceptor, and validatable interfaces
Provides callback support through Entity Listener and Callback methods
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships
Entity Relationships are bidirectional or unidirectional

45. What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
• Table per class hierarchy
• Table per subclass
• Table per concrete class

46: how do you implement one to one relationship in Hibernate with XML mapping?
For example you have table emp and emp_detail and assuming there is a one to one relationship between them.         For the above tables you have to create corresponding POJO classes and hbm.xml files.
So for emp table the java class is Employee.java with property empId and xml file is emp.hbm.xml.
And for emp_details the java class is EmployeeDetail.java (properties are name, address etc.) and xml file is empdetail.hbm.xml.
So the final code will look like as below
package com.JavaArtifacts.onetoone.mapping
public class Employee implements java.io.Serializable{
private Integer empId;
private EmployeeDetail empDetail;

}
package com. JavaArtifacts.onetoone.mapping
public class EmployeeDetail implements java.io.Serializable{
private Integer empId;
private Employee emp;
private String name;
private String address;
}

emp.hbm.xml

empdetails.hbm.xml

emp

46: How do you implement one to one relationship in Hibernate with java annotation?
Ans: Taking the same Employee and Employee Details example of the above question.
Employee.java
package com.JavaArtifacts.onetoone.mapping

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = “emp”)
public class Employee implements java.io.Serializable{
private Integer empId;
private EmployeeDetail empDetail;
public Employee(){}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = “EMP_ID”, unique = true, nullable = false)
public Integer getEmpId(){
return this.empId;
}
public void setEmpId(Integer empId){
this.empId = empId;
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = “emp”, cascade = CascadeType.ALL)
public EmployeeDetail getEmpDetail() {
return this.empDetail;
}
public void setEmpDetail(EmployeeDetail empDetail) {
this.empDetail = empDetail; }
}
File: EmployeeDetail.java
package com.JavaArtifacts.onetoone.mapping

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
@Entity
@Table(name = “emp_detail”)
public class EmployeeDetail implements java.io.Serializable {
private Integer empId;
private Employee emp;
private String name;
private String address;
public EmployeeDetail() {
}
public EmployeeDetail(Employee emp, String name, String address) {
this.emp = emp;
this.name = name;
this.address = address;
}
@GenericGenerator(name = “generator”, strategy = “foreign”,
parameters = @Parameter(name = “property”, value = “emp”))
@Id
@GeneratedValue(generator = “generator”)
@Column(name = “EMP_ID”, unique = true, nullable = false)
public Integer getEmpId() {
return this.empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Employee getEmp() {
return this.emp; }

public void setEmp(Employee emp) {
this.emp = emp;
}
@Column(name = “ADDRESS”, nullable = false, length = 400)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
@Column(name = “EMP_NAME”, nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Puts annotated classes Employee.java and EmployeeDetail.java in your Hibernate configuration file, and also MySQL connection details.

File : hibernate.cfg.xml

com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/empdb root password org.hibernate.dialect.MySQLDialect true

47 How do you implement one to many relationships in Hibernate?
Ans: For one to many relationships we can consider the example Author and Books (i.e. one Author can have written many books).
Below code will help you to understand how you can implement one to many relationship in hibernate.
File: Author.java
package com.JavaArtifacts.onetomany;

import java.util.Set;

public class Author implements java.io.Serializable{
private Integer authorId;
private String authorName;
private Set books;
// getter and setter
}

File: Book.java
package com. JavaArtifacts.onetomany;

public class Book implements java.io.Serializable{
private Author author;
private Integer bookId;
private String bookName;
// getter and setter
}

File: Author.hbm.xml

File: Book.hbm.xml

File: hibernate.cfg.xml

com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/testdb root password org.hibernate.dialect.MySQLDialect true true

48: How to implement one to many relationships with Annotation?
Ans: You can implement one to much relationship with the help of Annotation also. Below code will help you to understand the one to much relationship with java Annotation.

File : Author.java
package com.JavaArtifacts.onetomany;

import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = “Author”)
public class Author implements java.io.Serializable {
private Integer authorId;
private String authorName;
private Set books;
public Author() {
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = “AUTHOR_ID”, unique = true, nullable = false)
public Integer getAuthorId() {
return this.authorId;
}

public void setAuthorId(Integer authorId) {
this.authorId = authorId;
}

@Column(name = “AUTHOR_NAME”, nullable = false, length = 100)
public String getAuthorName() {
return this.authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = “author”)
public Set getBooks() {
return this.books;
}
public void setBooks(Set books) {
this.books = books;
}

}
File : Book.java
package com.JavaArtifacts.onetomany;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = “book”)
public class Book implements java.io.Serializable {
private Author author;
private Integer bookId;
private String bookName;
public Book() {
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = “BOOK_ID”, unique = true, nullable = false)
public Integer getBookId() {
return this.bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = “AUTHOR_ID”, nullable = false)
public Author getAuthor() {
return this.auther;
}
public void setAuther(Author author) {
this.auther = auther;
}
@Column(name = “BOOK_NAME”, length = 400, nullable=false)
public Float getBookName() {
return this.bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}

}
Hibernate Configuration File
Puts annotated classes Author.java and Book.java in hibernate.cfg.xml like this

File : hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/testdb root password org.hibernate.dialect.MySQLDialect true

49: What are the different types of caches in Hibernate?
Hibernate uses two different type of caches for objects:
first-level cache and second-level cache.
First level of cache is associated with Session object, while second-level of cache is associated with the SessionFactory object. By default, Hibernate uses first-level of cache on a per-transaction basis. Hibernate mainly use this cache to reduce the number of SQL queries it needs to generate within a given transaction.

50: What is Hibernate proxy?
Mapping of classes can be made into a proxy instead of a table. A proxy is returned when actually a load is called on a session. The proxy contains actual method to load the data. The proxy is created by default by Hibernate, for mapping a class to a file. The code to invoke Jdbc is contained in this class. 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.

 

Leave a Comment