Hibernate Notes




HIBERNATE INTERVIEW QNS AND ANSWERS :


1. What is Hibernate ?
A)Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programminglanguage. It provides a framework for mapping an object-oriented domain model to a relational database.

2.What is Java Persistence API(JPA) ?

A)Java Persistence API (JPA) provides specification for managing the relational data in applications. 

3. advantages of Hibernatle ?
A)
1. hibernate code is very clear,supports inheritance, associations and collections
2. hibernate provides HQL(hibernate query language) and transaction management.
3. also supports hibernate caching.

4. some of interfaces in hibernate?
A) Configuration, SessionFactory,  Session, Query, Transaction, Criteria

5.some important annotations used in hibernate ?
A) javax.persistence.Entity: Used to specify that model classes are entity beans.
  1. javax.persistence.Table: Used with entity beans to define database table name.
  2. 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.
  3. javax.persistence.Id: Used to define the primary key in the entity bean.
  4. javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
  5. javax.persistence.Column: Used to define the column name in database table.
  6. javax.persistence.GeneratedValue: Used to define the strategy to be used for generation of primary key. Used in conjunction with javax.persistence.GenerationType enum.
  7. javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as OneToManyManyToOne and ManyToMany
  8. 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



6. difference between openSession and getCurrentSession ?


A)

1. getCurrentSession() method returns the session bound to the context.

2. for this to work, we need to configure it in hibernate configuration file 

ex: <<property name="hibernate.current_session_context_class">thread</property>

3. If its not configured to thread, then we will get below exception.

Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!

4.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.

5. Hibernate Session objects are not thread safe, so we should not use it in multi-threaded environment.
  • openSession() method always opens a new session. 
  • We should close this session object once we are done with all the database operations.
  • Hibernate SessionFactory openStatelessSession() method returns instance of StatelessSession


7. difference between Hibernate Session get() and load() method

A)
  1. get method of Hibernate Session class returns null if object is not found in cache as well as on database while load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null
  2. get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading.
  3. Since load() throws exception when data is not found, we should use it only when we know data exists.
  4. We should use get() when we want to make sure data exists in the database.

8.Difference between First and Second level cache in Hibernate?
A)Hibernate provides caching at many levels e.g. first level cache at Session level, second level cache at the SessionFactory level, and query cache to cache frequently executed SQL queries
9. Hibernate Inheritance mapping stratagies ?
10. automatic dirty checking feature in hibernte?
11. types of association in hibernate ?
12. Lazyloading in hibernate?
13. Hibernate QueryLanguage (HQL) ?


The first level cache minimizes database access for the same object.

When you will call the get() method again for the same object from the same session, even after doing some updates on the object, it will return the object from the cache without accessing the database.

A)
3 ways of inheritance strategies in hibernate
1. Table per heirarchy
2. Table per concrete class
3. Table per subclass

A) calls update statement automatically on the object that are modified in transaction.

A) there are 4 types of hibernate associations as below
              1. One-to-One
              2. One-to-Many
              3. Many-to-one
              4. Many-to-Many

A) Lazyloading is loding child object on demand and it improves the performance. in hibernate default lazy loading enabled i.e   lazy="true" 

A) HQL is object oriented language. it like sql. 
advanteges of HQL are : easy to learn, no need to learn of sql, Database independent 
-----------------------------XXXXXXXXXXX---------------------------

Programs:


One-to-Many Association :


in a simply way : one-to-many mapping means that one row in a table is mapped to multiple rows in another table.



bidirectional association allows navigation from both "ends" of the association.

The mappedBy property is what we use to tell Hibernate which variable we are using to represent the parent class in our child class.


One to Many Mapping, One to Many Mapping in Hibernate, Hibernate One to Many Mapping Example

project structure :

Hibernate One To Many Mapping, One to Many Mapping in Hibernate, Hibernate One to Many Mapping Annotation Example


POM.XML


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.journaldev.hibernate</groupId>
  <artifactId>HibernateOneToManyMapping</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
  <dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>4.3.5.Final</version>
  </dependency>
  <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.0.5</version>
  </dependency>
  </dependencies>
  </project>


One To Many Mapping in Hibernate – Database Setup

We can use foreign key constraint for one to many mapping. Below is our database script for Cart and Items table.
setup.sql
CREATE TABLE `Cart` (
  `cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `total` decimal(10,0) NOT NULL,
  `name` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

CREATE TABLE `Items` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `cart_id` int(11) unsigned NOT NULL,
  `item_id` varchar(10) NOT NULL,
  `item_total` decimal(10,0) NOT NULL,
  `quantity` int(3) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `cart_id` (`cart_id`),
  CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

Hibernate One To Many Mapping Annotation Model Classes

Since we don’t have xml based mapping files, all the mapping related configurations will be done using JPA annotations in the model classes. If you understand the xml based mapping, it’s very simple and similar.
Cart1.java


import java.util.Set;

import javax.persistence.Column;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="CART")
public class Cart1 {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="cart_id")
private long id;
@Column(name="total")
private double total;
@Column(name="name")
private String name;
@OneToMany(mappedBy="cart1")
private Set<Items1> items1;
// Getter Setter methods for properties
}

Important point to note is the OneToMany annotation where mappedBy variable is used to define the property in Items1 class that will be used for the mapping purpose. So we should have a property named “cart1” in Items1 class. Don’t forget to include all the getter-setter methods.

Items1.java


import javax.persistence.Column;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="ITEMS")
public class Items1 {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private long id;
@Column(name="item_id")
private String itemId;
@Column(name="item_total")
private double itemTotal;
@Column(name="quantity")
private int quantity;
@ManyToOne
@JoinColumn(name="cart_id", nullable=false)
private Cart1 cart1;
//Hibernate requires no-args constructor
public Items1(){}
public Items1(String itemId, double total, int qty, Cart1 c){
this.itemId=itemId;
this.itemTotal=total;
this.quantity=qty;
this.cart1=c;
}
//Getter Setter methods
}

Most important point in above class is the ManyToOne annotation on Cart1 class variable and JoinColumnannotation to provide the column name for mapping.

-----------------------------------------------------------------

Hibernate Many to Many :

Many-to-Many mapping is usually implemented in database using a Join Table.

For example we can have Cart and Item table and Cart_Items table for many-to-many mapping.


No comments:

Post a Comment

JAVA NOTES

  click here  👉  Interview  Preparation : complete notes sql queries notes ============================================================ Con...