Hibernate Flashcards

1
Q

What is ORM ?

A

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is ORM (Object/Relational Mapping) used for?

A

Hibernate ORM is concerned with helping your application to achieve persistence. Specifically, Hibernate ORM is concerned with data persistence as it applies to relational databases (RDBMS).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Persistence?

A

Persistence simply means that we would like our application’s data to outlive the applications process. In Java terms, we would like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later.

RDBMS remain a very popular persistence mechanism and will so for the foreseeable future.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does ORM consists of ?

A

An ORM solution consists of the following four entities:
1 An API to perform basic CRUD operations on objects of persistent classes.
2 A language or API to specify queries that refer to classes and properties of classes.
3 A configurable facility for specifying mapping metadata.
4 A technique to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the CRUD operations

A

Create
Read
Update
Delete

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Hibernate Dirty Checking?

A

Dirty Checking is one of the features of hibernate. In dirty checking, hibernate automatically detects whether an object is modified (or) not and need to be updated. As long as the object is in persistent state i.e., bound to a particular Session(org.hibernate.Session). Hibernate monitors any changes to the objects and executes sql.

Note: For dirty checking to work, the object must exist in cache.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a Transaction and a Transaction object?

A

A transaction represents a unit of work. If you want the database to do some work for you, then you need to start a transaction. When you are finished interacting with the database, you end the transaction, and let the database know you are done.

A transaction is associated with a Session and is usually instantiated by a call to Session.beginTransaction(). A single session might span multiple transactions since the notion of a session (a conversation between the application and the datastore) is of coarser granularity than the notion of a transaction. However, it is intended that there be at most one uncommitted Transaction associated with a particular Session at any time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is Hibernate Lazy Association Fetching?

A

Lazy loading means that an entity will be loaded only when you actually accesses the entity for the first time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the ORM levels ?

A
The ORM levels are: 
● Pure relational (stored procedure.) 
● Light objects mapping (JDBC) 
● Medium object mapping 
● Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is Hibernate?

A

Hibernate is a high-performance Object/Relational persistence. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Why do you need ORM tools like Hibernate?

A
The main advantage of ORM like hibernate is that it shields developers from messy SQL. 
● Improved productivity 
○ High-level object-oriented API 
○ Less Java code to write 
○ No SQL to write 

● Improved performance
○ Sophisticated caching
○ Lazy loading
○ Eager loading

● Improved maintainability
○ A lot less code to write

● Improved portability
○ ORM framework generates database-specific SQL for you

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the core interfaces are of the Hibernate framework?

A

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

  1. Session Interface
  2. SessionFactory interface
  3. Configuration Interface
  4. Transaction Interface
  5. Query and Criteria interface
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the types of Hibernate instance states ?

A

Three types of instance states:
1. Transient : This instance is never been associated with any one of the persistence process. This does not have persistent identity like primary key value.

  1. 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
  2. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the essential properties of a transaction?

A

Atomicity
Atomicity takes individual operations and turns them into an all-or-nothing unit of work, succeeding if and only if all contained operations succeed.

A transaction might encapsulate a state change (unless it is a read-only one). A transaction must always leave the system in a consistent state, no matter how many concurrent transactions are interleaved at any given time.

Consistency
Consistency means that constraints are enforced for every committed transaction. That implies that all Keys, Data types, Checks and Trigger are successful and no constraint violation is triggered.

Isolation
Transactions are concurrency control mechanisms, and they deliver consistency even when being interleaved. Isolation brings us the benefit of hiding uncommitted state changes from the outside world, as failing transactions shouldn’t ever corrupt the state of the system. Isolation is achieved through concurrency control using pessimistic or optimistic locking mechanisms.

Durability
A successful transaction must permanently change the state of a system, and before ending it, the state changes are recorded in a persisted transaction log. If our system is suddenly affected by a system crash or a power outage, then all unfinished committed transactions may be replayed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are Transaction Isolation Levels?

A

The transaction isolation level indicates the degree to which two transactions interact with each other over the same data. The transaction problems that can occur are: lost update, dirty read, unrepeatable read, and phantom read.

Read uncommitted isolation levels This is the lowest isolation level which can also be called as dirty read. Using this, you can read uncommitted data which can be rolled back at any point. With this level, SQL server uses share lock while reading data.

Read committed isolation levels With this level, uncommitted data can’t be read. This is default isolation level and uses shared lock while reading data.
Repeatable read isolation levels It locks all the data that is used in the query.

Serializable isolation levels It locks data set until the transaction will be completed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between the first and second level caches in Hibernate?

A

First level cache
● Default
● Transaction scoped.
● Formed by the session object.
● Single session availability.
● Guarantees object identity inside a transaction. Second level cache
● Optional/pluggable
● Might be scoped to the process or cluster.
● Formed by the SessionFactory object.
● Multiple session availability.
● Can be configured on per class or per association basis. First-level cache First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction. Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Name some second level (L2) cache providers for Hibernate.

A

Ehcache: is an open source, standards-based cache that boosts performance, offloads your database, and simplifies scalability.

OSCache: is a caching solution that includes a JSP tag library and set of classes to perform fine grained dynamic caching of JSP content, servlet responses or arbitrary objects.

SwarmCache: is a simple but effective distributed cache. It uses IP multicast to efficiently communicate with any number of hosts on a LAN. It is specifically designed for use by clustered, database-driven web applications.

JBoss Cache’s: goal is to provide enterprise-grade clustering solutions to Java-based frameworks, application servers or custom-designed Java SE applications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is Transaction dirty read?

A

Dirty read occurs wherein one transaction is changing the tuple/record, and a second transaction can read this tuple/record before the original change has been committed or rolled back.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is Transaction lost update?

A

A lost update occurs when two different transactions are trying to update the same column on the same row within a database at the same time. Typically, one transaction updates a particular column in a particular row, while another that began very shortly afterward did not see this update before updating the same value itself. The result of the first transaction is then “lost”, as it is simply overwritten by the second transaction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is Transaction repeatable read?

A

Specifies that statements cannot read data that has been modified but not yet committed by other transactions and that no other transactions can modify data that has been read by the current transaction until the current transaction completes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is Transaction Phantom Read?

A

Data getting changed in current transaction by other transactions is called Phantom Reads. New rows can be added by other transactions, so you get different number of rows by firing same query in current transaction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do you configure an L2 cache in Hibernate?

A

● Choose an L2 cache vendor that has the desired properties.
● In hibernate.cfg.xml include a cache provider tag:

“property name=”“hibernate.cache.provider_class”
org.hibernate.cache.EhCacheProvider property “

● Set the cache properties in the cache provider’s xml or use annotations in the persistent class. Example:
“cachename=”“com.somecompany.someproject.domain.Country”” maxElementsInMemory=”“10000”” eternal=”“false”” timeToIdleSeconds=”“300”” timeToLiveSeconds=”“600”” overflowToDisk=”“true”” /”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are some common JPA annotations used in Hibernate?

A

javax.persistence.*

@Entity: Annotate all your entity beans with @Entity.

@Table: Specify the database table this Entity maps to using the name attribute of @Table annotation. In the example below, the data will be stored in ‘company’ table in the database.

@Column: Specify the column mapping using @Column annotation.

@Id: Annotate the id column using @Id.

@GeneratedValue: Let database generate (auto-increment) the id column.

@OneToOne
@ManyToOne
@OneToMany
@ManyToMany

24
Q

What is the difference in the hibernate.cfg.xml for the mapped (hbm) and annotation driven class?

A

Mapping file implementation: mapping resource=”myTable.hbm.xml” Annotated POJO implementation: mapping class=”myTable”

25
Q

What is the need for Hibernate xml mapping file?

A

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.

26
Q

What are the important tags of hibernate.cfg.xml?

A

Hibernate Configuration
Session Factory
Property Name
Mapping Resources

27
Q

What role does the Session interface play in Hibernate?

A

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role:
● Wraps a JDBC connection
● Factory for Transaction
● Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

28
Q

What role does the SessionFactory interface play in Hibernate?

A

What is the general flow of a Hibernate communication with the RThe application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory();DBMS?

29
Q

What is the general flow of a Hibernate communication with the RDBMS?

A

The general flow of Hibernate communication with RDBMS is :
● Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
● Create session factory from configuration object
● Get one session from this session factory
● Create HQL Query
● Execute query to get list containing Java objects

30
Q

What is Hibernate Query Language (HQL)?

A

Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database.

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.

Although you can use SQL statements directly with Hibernate using Native SQL but I would recommend to use HQL whenever possible to avoid database portability hassles, and to take advantage of Hibernate’s SQL generation and caching strategies.

Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

31
Q

How do you map Java Objects with Database tables?

A
● First we need to write Java domain objects (beans with setter and getter). 
● Write hbm.xml, where we map java class to table and database columns to Java class variables.
32
Q

What’s the difference between load() and get()?

A

Hibernate - Difference between load() and get() in Hibernate. Java and Advanced Java&raquo_space; Hibernate - Part 2 Next Page » Explain the difference between load() and get() in Hibernate. Difference between load() and get(): load() :
1. Use this method if it is sure that the objects exist.
2. The load() method throws an exception,when the unique id could not found in the database.
3. The load() method returns proxy by default and the data base will not be effected until the invocation of the proxy. get() :
1. Use this method if it is not sure that the objects exist.
2. Returns null when the unique id is unavailable in the database.
3. The data base will be effected immediately. load()
● Only use the load() method if you are sure that the object exists.
● load() method will throw an exception if the unique id is not found in the database.
● load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get()
● If you are not sure that the object exists, then use one of the get() methods.
● get() method will return null if the unique id is not found in the database.
● get() will hit the database immediately.

33
Q

What is the difference between and merge and update?

A

update () : When the session does not contain the persistent instance with the same identifier, and if it is sure use update for the data persistence in the hibernate.

merge () : Irrespective of the state of a session, if there is a need to save the modifications at any given time, use merge().

34
Q

How do you define sequence generated primary key in hibernate?

A

Using generator tag
@GeneratedValue(strategy=GenerationType.AUTO)

@GenericGenerator(name=”kaugen” , strategy=”increment”) @GeneratedValue(generator=”kaugen”)

35
Q

Define cascade and inverse option in one-many mapping?

A
  1. inverse This is used to decide which side is the relationship owner to manage the relationship (insert or update of the foreign key column).
  2. cascade In cascade, after one operation (save, update and delete) is done, it decide whether it need to call other operations (save, update and delete) on another entities which has relationship with each other. cascade - enable operations to cascade to child entities. cascade=”all|none|save-update|delete|all-delete-orphan” inverse - mark this collection as the “inverse” end of a bidirectional association. inverse=”true|false” Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
36
Q

What is a Named SQL Query?

A

A named query is a SQL expression represented as a table. In a named query, you can specify an SQL expression to select rows and columns returned from one or more tables in one or more data sources.

Named SQL queries are defined in the mapping xml document and called wherever required.

37
Q

How do you invoke Stored Procedures?

A

https://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/

38
Q

Explain Criteria API

A

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.

The Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object that returns instances of the persistence object’s class when your application executes a criteria query.

39
Q

How do you switch between different relational databases?

A

For an application managed datasource: In hibernate.cfg.xml change the driver properties (URL, username, and password) to the new database. Use the appropriate connector jar for the new database in the project classpath. For a server managed datasource: In the hibernate.cfg.xml change the JNDI name to the one for the new database. In either case: In hibernate.cfg.xml change the property tag: name = dialect to the new database dialect. No changes to the java code are required!

40
Q

If you want to see the Hibernate generated SQL statements on console, what should we do?

A

In Hibernate configuration file set as follows: property name=”show_sql”true property

41
Q

What is the difference between sorted and ordered collection in hibernate?

A

Sorted Collection : - The sorted collection is a collection that is sorted using the Java collections framework. The sorting is done in the memory of JVM that is running hibernate, soon after reading the data from the database using Java Comparator - The less the collection the more the efficient of sorting Ordered Collection : - The order collections will also sorts a collection by using the order by clause for the results fetched. - The more the collection, the more efficient of sorting. sorted 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. If your collection is not large, it will be more efficient way to sort it. order collection Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval. If your collection is very large, it will be more efficient way to sort it .

42
Q

What are the Collection types in Hibernate?

A
List
Set
SortedSet
Map
SortedMap
Collection
43
Q

What are the ways to express joins in HQL?

A

HQL provides four ways of expressing (inner and outer) joins:-
● An implicit association join
● An ordinary join in the FROM clause
● A fetch join in the FROM clause.
● A theta-style join in the WHERE clause.

44
Q

What is Hibernate proxy?

A

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

45
Q

What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

A

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set.
● dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
● dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

46
Q

What do you mean by fetching strategy ?

A

A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

  1. fetch-“join” = Disable the lazy loading, always load all the collections and entities.
  2. fetch-“select” (default) = Lazy load all the collections and entities.
  3. batch-size=”N” = Fetching up to ‘N’ collections or entities, Not record.
  4. fetch-“subselect” = Group its collection into a sub select statement.
47
Q

What is automatic dirty checking?

A

Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

48
Q

What is transactional write-behind?

A

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.

49
Q

What are Callback interfaces?

A

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.

50
Q

What are the types of inheritance models in Hibernate?

A
There are three types of inheritance models in Hibernate: 
● Table per class hierarchy 
● Table per subclass 
● Table per concrete class
51
Q

What is the advantage of Hibernate over jdbc?

A
JDBC 
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. In JDBC there is no check that always every user has updated data. This check has to be added by the developer. Hibernate Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.
52
Q

What is Session Interface?

A

Session Interface : The basic interface for all hibernate applications. The instances are light weighted and can be created and destroyed without expensive process.

53
Q

What is SessionFactory interface?

A

SessionFactory interface : The delivery of session objects to hibernate applications is done by this interface. For the whole application, there will be generally one SessionFactory and can be shared by all the application threads.

54
Q

What is Configuration Interface?

A

Configuration Interface : Hibernate bootstrap action is configured by this interface. The location specification is specified by specific mapping documents, is done by the instance of this interface.

55
Q

What is Transaction Interface?

A

Transaction Interface : This is an optional interface. This interface is used to abstract the code from a transaction that is implemented such as a JDBC / JTA transaction.

56
Q

Query and Criteria interface

A

Query and Criteria interface : The queries from the user are allowed by this interface apart from controlling the flow of the query execution.