1.What is the difference between annotations @Id and @GeneratedValue

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id") 
private Integer id;

@Id
In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

@GeneratedValue
The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which indicates that the persistence provider must assign primary keys for the entity using a database identity column.

Notes

  • The difference between @Id and @GeneratedValue can be clearly observed while switching from OneToOne and OneToMany Mapping where the OneToOne Mapping requires only ID to insert values for both the table whereas OneToMany Mapping table insertion depends on values inserted in one and other table.
  • @GeneratedValue creates a sequence maintained at database

2.Sequence vs Identity
Sequence and identity both used to generate auto number but the major difference is Identity is a table dependant and Sequence is independent from table.

If you have a scenario where you need to maintain an auto number globally (in multiple tables), also you need to restart you interval after particular number and you need to cache it also for performance, here is the place where we need sequence and not identity.

When @Id is used the value count starts from 0 where as when @GeneratedValue is used the count starts from 1

3.What is difference between OneToMany and ManyToOne Mapping?
For example, if a user, a company, a provider all have many addresses, it would make sense to have a unidirectional between every of them and Address, and have Address not know about their owner.

Suppose you have a User and a Message, where a user can have thousands of messages, it could make sense to model it only as a ManyToOne from Message to User, because you’ll rarely ask for all the messages of a user anyway.

In One-to-many you keep the reference of many objects via (set, list) for the associated objects. You may not access the parent object from the items it is associated with. E.g. A person has many skills. If you go to a particular skill you may not access the persons possessing such skills. This means given a Skill ,s, you’ll not be able to do s.persons.

In Many-to-one many items/objects will have reference to a particular object. E.g. Users x and y apply to some job k. So both classes will have their attribute Job job set to k but given a reference to the job k you many not access the objects that have it as an attribute job. So to answer the question “Which users have applied to the job k?”, you’ll have to go through the Users list.

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: Each “child” Skill has a single pointer back up to the Person (which is not shown in your code)

One-to-Many: One Person Has Many Skills, a Skill is not reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: Each “child” Skill has a single pointer back up to the Person (which is not shown in your code)

Many-to-Many: One Person Has Many Skills, a Skill is reused between Person(s)
Unidirectional: A Person can directly reference Skills via its Set
Bidirectional: A Skill has a Set of Person(s) which relate to it.

4.Difference between Unidirectional and Bidirectional associations?
Bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions.

When we have a bidirectional relationship between objects, it means that we are able to access Object A from Object B, and Object B from Object A.

Unidirectional – means only allow navigating from one side of the mapping to another. For example in the case of a one-many mapping, only allow navigation from the one side to the many side. Bi-directional means to allow navigation both ways.


More Details in Link

MappedBy signals hibernate that the key for the relationship is on the other side.
This means that although you link 2 tables together, only 1 of those tables has a foreign key constraint to the other one. MappedBy allows you to still link from the table not containing the constraint to the other table.

With the mappedBy, you directly tell Hibernate that one table owns the relationship, and therefore it is stored as a column of that table.

Question have several Answer,But the answer is owned by one and only one Question.

5.Eager vs Lazy Initialization?
By default hibernate follows lazy initialization.Actual data will be fetched only during accessing object value.Say you have a Class(Entity) and List(Value) in the class.The Hibernate creates proxy class which fetches values only at the upper level.By default, for all collection and map objects the fetching rule is FetchType.LAZY and for other instances it follows the FetchType.EAGER policy.Lazy initialization improves performance by avoiding unnecessary computation and reduce memory requirements.Eager initialization takes more memory consumption and processing speed is slow.

UserDetails.java

.
.
@ElementCollection(fetch=FetchType.EAGER)
private List<Address> arrList = new ArrayList<Address>();
.
.
.

AccessTable.java

   SessionFactory sessionFact = createSessionFactory();
   Session session = sessionFact.openSession();	
		
   UserDetails user = null;
   session = sessionFact.openSession();		
   user = (UserDetails)session.get(UserDetails.class, 50);
   session.close();
   System.out.println("Size of List-" + user.getArrList().size());

Output

 Size of List- 2

In eager initialization all the class object details will be taken at assignment to object itself and not during accessing the list object of that class.

6.Difference between Embedded and Embeddable?
There are two types of objects in Hibernate
1. Value Object
2. Entities

Value Objects are the objects which can not stand alone. Take Address, for example. If you say address, people will ask whose address is this. So it can not stand alone.Entity Objects are those who can stand alone like College and Student.

Refer here

7.Difference between createQuery vs createSQLQuery vs createCriteria?
Refer here

8.When to prefer IBatis over Hibernate
Hibernate works better if your view is more object-centric. If however you view is more database-centric then Ibatis is a much stronger choice.Hibernate is object-relation mapping framework (ORM) which maps Java classes to database tables. MyBatis is persistence framework – not ORM. It maps SQL statements to Java methods.Hibernate has first level cache which is impossible to disable. It means that if you query item through ORM and then delete it directly with SQL, it stays in the cache. You can explicitly clear the cache to get the most updated results from database but unfortunately such behavior may bring errors like “detached entity passed to persist”

If you perform Create/Update/Delete of some complex domain entities Hibernate works well allowing you to just make a POJO and persist/update it. It also does this quickly, unless your domain is quite large.

Run analytic fetch queries (i.e. summation/aggregation queries). IBatis is great for fetch queries where you just want an answer.Hibernate would attempt to load the entire object graph and you’d need to start tuning queries with LazyLoading tricks to keep it working on a large domain. Conversely if you just want some analytic POJO page, the myBatis implementation of the same query would be trivial.

9.Ordered Collection vs Sorted Colection

sorted collection order 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. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .

10.What is the of use caching in hibernate? Can we disable the first level cache?
Caching helps in reducing the hits over database.First level cache cannot be disabled but by using evict() we can make hibernate to fetch the entity everytime from db

  1. First level cache is associated with “session” object and other session objects in application can not see it.
  2. The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
  3. First level cache is enabled by default and you can not disable it.
  4. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.
  5. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
  6. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method.
  7. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

You should therefor either use the evict() or clear() method to force a query to the database.

Please Refer here

11.What is automatic dirty checking in hibernate?
Whenever an entity is loaded through hibernate, it makes an additional copy of that whole entity object along with the all entity’s property values. By entity, we mean each persistent object of that entity type. Within the Persistence Context, Hibernate has a copy of all persistent objects that were loaded from the database. It compares these persistent objects with these objects to detect the objects that have been modified or are dirty. This is the default implementation.
Please Refer here

12.How Hibernate works internally?
Refer here

13.Difference between get and load in hibernate?
get() involves database hit if object doesn’t exists in Session Cache and returns a fully initialized object which may involve several database call while load method can return proxy in place and only initialize the object or hit the database if any method other than getId() is called on persistent or entity object. This lazy initialization can save couple of database round-trip which result in better performance. load() method throws ObjectNotFoundException if object is not found on cache as well as on database but never return null

Session session = SessionFactory.getCurrentSession();
Employee Employee = (Employee) session.get(Employee.class, EmployeeID);

//Example of calling load method of Hiberante Session
Session session = SessionFactory.getCurrentSession();
Employee Employee = (Employee) session.load(Employee.class, EmployeeID);

14.Difference between First and Second Level Cache in Hibernate
First Level Cache

  1. The first level cache minimizes database access for the same object. For example, if you call the get() method to access Employee object with id = 1 from one session, it will go the database and load the object into memory, but it will also cache the object in the first level cache.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
  2. This session level cache greatly improves the performance of Java application by minimizing database roundtrips and executing less number of queries. For example, if an object is modified several times within the same transaction, then Hibernate will only generate one SQL UPDATE statement at the end of the transaction, containing all the modification.
  3. Since this cache is associated with the Session object, which is a short-lived object in Hibernate, as soon as you close the session, all the information held in the cache is lost. So, if you try to load the same object using the get() method, Hibernate will go to the database again and fetch the record.

Second Level Cache

  1. The second level cache is provided with the help of caching providers e.g. EhCache and OSCache.
  2. Depending upon which cache you want to use, you can configure them in the Hibernate Configuration file.Once configured, every request for an object will go to the second level cache if it is not found in the first level cache. It won’t hit the database without consulting second level cache, which means improved performance.
  3. First level cache is associated with Session Object, while the Second level cache is associated with the SessionFactory object. This means first level cache’s scope is limited to session level while second level cache’s scope is at the application level. Since Session object is created on demand from the SessionFactory and it’s destroyed once the
  4. First level cache is by default enabled in Hibernate, while the second level cache is optional. If you need it then you need to explicitly enable the second level cache on Hibernate configuration file i.e. the hibernate.cfg.xml file.

You can use the hibernate.cache.provider_class and hibernate.cache.use_second_level_cache properties to enable the second level cache in Hibernate. The first one is the name of the class which implements Second level cache and could be different, depending upon which cache you use e.g. EhCache or OSCache.By default, hibernate.cache.provider_class is set to org.hibernate.cache.NoCacheProvider class, which means the second level cache is disabled. You can enable it by setting something like org.hibernate.cache.EhCacheProvider if you want to use EhCache as the second level cache.Here is a sample configuration to configure Second level cache with EhCache, Don’t forget to include hibernate-ehcache.jar into your classpath

<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

15.Difference between Transaction manager and Entity Manager
Entity Manager is responsible for listener, entities, relationships, persist lifecycle of them and this interface defines the methods that are used to interact with the persistence context associated with an specific persistence context.TransactionManager is responsible for transactional data access, giving support to all the transaction that need to occurs within your application.Transaction manager belongs with the Service layer, Entity Manager belong to the persistence layer

16.Hibernate SessionFactory vs EntityManagerFactory
EntityManagerFactory and EntityManager are defined by the JPA standard. SessionFactory and Session are hibernate-specific. The EntityManager invokes the hibernate session under the hood

17.Why prefer JPA API over the proprietary Hibernate?
The JPA API is cleaner than the Hibernate, Offers something that you can reuse in more other projects relying on a different implementation.
You can get the Hibernate Session from the JPA EntityManager

Session session = entityManager.unwrap(Session.class);

By using EntityManager, the code is no longer tightly coupled with hibernate

JPA       - javax.persistence.EntityManager
Hibernate - org.hibernate.ejb.HibernateEntityManager

Comments are closed.