Hibernate Flashcards
What is Hibernate? What is JPA?
Hibernate is an object relational mapping tool for Java. It provides a framework for mapping an object oriented model to a relational database. Hibernate replaces direct database access with high level object handling functions
JPA (Java Persistence API) is a specification of Java that is used to access, manage and persist data between Java and a database. JPA doesnt perform any operations by itself, so it requires Hibernate to perform the operations. Hibernate is an implementation of JPA. It is an ORM tool
What is the benefit of using hibernate over JDBC?
- Its faster
- It is object oriented which means that devs can focus on the code rather than persistence logic since Hibernate takes care of the connections and crud operations
- Its modular (we need only change the hibernate.cfg.xml)
- It uses caching, so data is stored in the heap so it can be retrieved faster later
- it uses connection pooling, so we dont need to constantly restart database connection
- JDBC code is not portable across multiple database software
What are some JPA annotations that we have worked with? What do they do? How do you specify multiplicity relationships with JPA annotations?
@Entity - Tells the database that this will be an object
@Table - Tells the database that the object will be a table
@Id - tells the database that this will be the primary key
@Column - Tells the database the name of the column
@GeneratedValue - How we auto increment a value
@Transient - Tells the database not to save this field
Multiplicity relationships: @OneToOne @OneToMany @ManyToOne @ManyToMany
What are the interfaces of Hibernate?
- Configuration - Used to specify the location of the configuration file
- SessionFactory - Used to create an instance of a session
- Session Interface - Provides methods to store and receive objects from the database
- Query/Criteria API - Allows the user to perform queries against the database. Query - HQL | Criteria - Itself
- Transaction Interface - used to commit operations
How would you set up Hibernate? What files are you editing, what goes in them, etc.?
- Create the persistence class
- Must contain a no args constructor, needs an identifier property such as an id, declare getter and setter - Create the config file
- In the hibernate.cfg.xml file, session factory with properties to connect to sql - create the class that retrieves or stores in the DB
- Lead the jar file
- Run the Hibernate App
What ways are available to you to map an object to database entities in Hibernate
Using annotations from JPA to tell hibernate what objects are going to the database
using XML files to define the table and columns
In the session interface, what is the difference between save and persist methods? Get and load methods? Update and merge methods?
save() vs persist(): Save returns generated identity value, persist returns void
get() vs load(): Get fetches an object from a database or hibernate cache, load returns a proxy
update() vs merge(): Update will only save the data if the object does not exist in the database, merge updates regardless of whether it exists or not
What are the different session methods?
beginTransaction() - used to enable a transaction
save() and persist() - results in an SQL insert
update() and merge() - results in an SQL update
get() and laod() - results in an SQL select
saveOrUpdate() - results in an SQL insert or update
createQuery() - creates an SQL query
flush() - syncs the in memory session with the database
delete() - removes an instance from the database
What is the difference between Eager and Lazy fetching and how do you setup either?
Eager fetching is used to fetch all information associated with the call
Lazy fetching is used to only fetch the information requested
They are both setup in annotations, if you want to lazy or eager load (fetch = FetchType.Lazy/Eager)
under what circumstances would your program throw a LazyInitializationException?
When you try to access data that hasn’t been fetched yet outside of a session context, like when the session is closed
What are the 3 ways to make a query using Hibernate?
- HQL - Hibernate Query Langage: Creates a complex query by using a combination of SQL and OOP. HQL targets Java Objects, not SQL tables - session.createQuery()
- Criteria API: Creates complex queries programmatically, so it only uses OOP and targets Java objects. It takes criteria and restrictions rather than SQL code - session.createCriteria()
- Native SQL: Creates complex queries using plain SQL to target tables - session.createNativeQuery()
What is HQL? What makes it different from SQL?
HQL - Hibernate Query Language is an object oriented query language that works with objects and their properties rather than tables.
What is the Criteria API? Can you perform all DDL and DML commands with it? How do Restrictions and Projections work within this API?
Criteria API creates dynamic queries programmatically, so it only targets Java objects. You cant do DDL or DML commands with Criteria API as it is primarily for queries. Restrictions act similarly to “where” in SQL as it specifies what information is selected. Projections is used to read parts of an entity from the database - ex. select empName from employee;
What is caching? What is the difference between L1 and L2 cache?
It is a mechanism used to enhance the performance of a system by storing recently used data to reduce the number of hits to the database.
L1 caching is a mandatory cache that all requests in a session must pass through - only accessible to the session
L2 caching is a SessionFactory level cache and is available through all sessions - accessible through all sessions
How do you enable second level caching?
In order to use second level caching, you must tell hibernate that it is enabled by adding the library dependencies of a cache provider to the pom.xml, then enable second level caching in the hibernate.cfg.xml file by adding
hibernate. cache.user_second_level_cache
hibernate. cache.region.factory_class
Then you have to add the Cacheable annotation to make the entity eligible for second level caching
What are NamedQueries?
NamedQueries are statically defined queries with predefined query strings. NamedQueries can be defined by annotation in the object or in mapping files
Can you write native SQL with Hibernate? Is this a good idea?
Yes you can use SQL queries using NativeQuery, and you would want to use this if you want to utilize DDL or DML operations. However, SQL doesnt play well with caches, so it flushes everything before it executes
What are the configuration options for hibernate?
dialect - makes hibernate generate appropriate SQL queries
connection. driver_class - The JDBC driver class
connection. url - JDBC url to the database
connection. username - database username
connection. password - database password
connection. pool_size - limits the number of connections
How do you specify the SQL dialect?
By using the dialect property in the hibernate.cfg.xml file
What data must be specified for the SessionFactory?
Username Password URL to the database The JDBC driver class Connection pool size dialect hbm2ddl
What is hbm2ddl?
It is a hibernate configuration property used to validate and export schema DDL to the database when the SessionFactory is created.
How would you configure Hibernate to print the console all SQL statements that run?
By setting the “show_sql” property to true
What are the different object states in Hibernate? What methods move objects to different states?
Transient - When an object is created using the new() operator, it is transient as it has no connection to the hibernate session yet – new()
Persistent - When the object becomes mapped to the database, it becomes persistent as it is now connected to the hibernate session – save() / persist()
Detached - When the session is closed, the object becomes detached – clear() / evict() / close()
What is a proxy? When does the proxy resolve to the real object?
A proxy is a subclass of the real class being loaded. Only when one of its methods are called will it load the real object
What is the difference between Dynamic Insert and Dynamic Update?
When the Dynamic Insert property is set to true, hibernate does not include null values for properties that are not set by the application during an insert.
When the Dynamic Update property is set to true, hibernate does not include unmodified properties in the update
What is automatic dirty checking?
Automatic dirty checking automatically saves and updates the database with persistent objects when a session is flushed or a transaction is committed without needing to explicitly call for it
What is Transactional Write Behind?
In order to reduce trips to the database, a transactional write behind sets a minimum number of SQL queries and waits to get to that number before executing them in one transaction
Explain how transaction propagation works
Transactional propagation defines how transactions relate to each other and decides how a component or service will work depending on if it already has a transaction created