Hibernate is a ORM tool which offer lots of advantages over plain JDBC.
Database independent
You can work with any database you want like oracle,mysql,db2,sql server ,etc. Using hibernate you won't worry about writing database specific queries and syntax. It's provides HQL (Hibernate Query Language), which is compatible with any database server. You just need to write queries in HQL, at the end hibernate converts HQL to underlying database and executes it.
OOP concepts
In ORM, you will map a database table with java object called "Entity". So once you map these,you will get advantages of OOP concepts like inheritance, encapsulation,associations etc that are not available in the JDBC API.
Caching mechanism - which improves performance
1st level & 2nd level cache provided hibernate means you don't need to hit database for similar queries, you can cache it and use it from buffered memory to improve performance.
- First-level is a mandatory Session cache.
- Second-level is an optional cache. Hibernate has a lot of cache providers for this level, the most popular are: EHCache, OSCache, warmCache, JBoss Cache, etc.
- Query-level is an optional cache for query result sets.
Lazy loading
Supports Lazy loading (also called n+1 problem in Hibernate). Take an example-parent class has n number of child class. So When you want information from only 1 child class,there is no meaning of loading n child classes.This is called lazy loading (Load only thing which you want).
- Supports JPA annotations, means the code is portable to other ORM frameworks.
- Connection pooling
- Bulk updates
- Built-in support for explicit locking and optimistic concurrency control.
- Allows you to transform the ResultSet into Entities or DTO (Data Transfer Object).
- You do not need to handle exceptions.Hibernate allows database management (for example creating tables), JDBC can only work with existing DB tables.
- Hibernate has capability to generate primary keys automatically while we are storing the records into database.
- Getting pagination in hibernate is quite simple.
- Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One
In terms of disadvantages of using other persistent layer:-
Boilerplate code issue
For Dao layer, need to write same code in several files in the same application, but spring data jpa has eliminated this. - providing JPARepository
Hibernate Inheritance Mapping
Compared to JDBC we have one main advantage in hibernate, which is hibernate inheritance. Suppose if we have base and derived classes, now if we save derived(sub) class object, base class object will also be stored into the database.
Hibernate supports 3 types of Inheritance Mappings:
Table per class hierarchy(Single Table Strategy)
Table per sub-class hierarchy(Join Strategy)
Table per concrete class hierarchy
- In the above case, we can map the whole hierarchy into single table, here we use one more discriminator column i.e. TYPE.
- Performance wise better than all strategies because no joins or sub-selects need to be performed.
- Tables are not normalized.
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="TYPE",
discriminatorType=DiscriminatorType.STRING
)
- In the above case, we have a single table for each class in the hierarchy but subclass mapped tables are related to parent class mapped table by primary key and foreign key relationship.
- It’s highly normalized but performance is not good.
@Inheritance(strategy=InheritanceType.JOINED)
- In the above case, we have one table for each concrete class in the hierarchy. But duplicate column is added in subclass tables.
- slightly more normalized than table per class strategy
- To support polymorphism either container has to do multiple trips to database or use SQL UNION kind of feature.
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
Association Mappings between Hibernate Entities
one-to-one association
1. Using foreign key association:-
a foreign key column is created in owner entity.
if we make Employee owner, then a extra column “ACCOUNT_ID” will be created in Employee table. This column will store the foreign key for Account table.
many-to-many association
Database independent
You can work with any database you want like oracle,mysql,db2,sql server ,etc. Using hibernate you won't worry about writing database specific queries and syntax. It's provides HQL (Hibernate Query Language), which is compatible with any database server. You just need to write queries in HQL, at the end hibernate converts HQL to underlying database and executes it.
OOP concepts
In ORM, you will map a database table with java object called "Entity". So once you map these,you will get advantages of OOP concepts like inheritance, encapsulation,associations etc that are not available in the JDBC API.
Caching mechanism - which improves performance
1st level & 2nd level cache provided hibernate means you don't need to hit database for similar queries, you can cache it and use it from buffered memory to improve performance.
- First-level is a mandatory Session cache.
- Second-level is an optional cache. Hibernate has a lot of cache providers for this level, the most popular are: EHCache, OSCache, warmCache, JBoss Cache, etc.
- Query-level is an optional cache for query result sets.
Lazy loading
Supports Lazy loading (also called n+1 problem in Hibernate). Take an example-parent class has n number of child class. So When you want information from only 1 child class,there is no meaning of loading n child classes.This is called lazy loading (Load only thing which you want).
- Supports JPA annotations, means the code is portable to other ORM frameworks.
- Connection pooling
- Bulk updates
- Built-in support for explicit locking and optimistic concurrency control.
- Allows you to transform the ResultSet into Entities or DTO (Data Transfer Object).
- You do not need to handle exceptions.Hibernate allows database management (for example creating tables), JDBC can only work with existing DB tables.
- Hibernate has capability to generate primary keys automatically while we are storing the records into database.
- Getting pagination in hibernate is quite simple.
- Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One
In terms of disadvantages of using other persistent layer:-
Boilerplate code issue
For Dao layer, need to write same code in several files in the same application, but spring data jpa has eliminated this. - providing JPARepository
Hibernate Inheritance Mapping
Compared to JDBC we have one main advantage in hibernate, which is hibernate inheritance. Suppose if we have base and derived classes, now if we save derived(sub) class object, base class object will also be stored into the database.
Hibernate supports 3 types of Inheritance Mappings:
Table per class hierarchy(Single Table Strategy)
Table per sub-class hierarchy(Join Strategy)
Table per concrete class hierarchy
- In the above case, we can map the whole hierarchy into single table, here we use one more discriminator column i.e. TYPE.
- Performance wise better than all strategies because no joins or sub-selects need to be performed.
- Tables are not normalized.
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name="TYPE",
discriminatorType=DiscriminatorType.STRING
)
- In the above case, we have a single table for each class in the hierarchy but subclass mapped tables are related to parent class mapped table by primary key and foreign key relationship.
- It’s highly normalized but performance is not good.
@Inheritance(strategy=InheritanceType.JOINED)
- In the above case, we have one table for each concrete class in the hierarchy. But duplicate column is added in subclass tables.
- slightly more normalized than table per class strategy
- To support polymorphism either container has to do multiple trips to database or use SQL UNION kind of feature.
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
Association Mappings between Hibernate Entities
one-to-one association
1. Using foreign key association:-
a foreign key column is created in owner entity.
if we make Employee owner, then a extra column “ACCOUNT_ID” will be created in Employee table. This column will store the foreign key for Account table.
To make such association, refer the AccountEntity class in EmployeeEntity owner class as follow:
//EmployeeEntity
@OneToOne
@JoinColumn(name="ACCOUNT_ID", referencedColumnName=”ID”)
private AccountEntity account;
|
In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side.
//AccountEntity
@OneToOne(mappedBy="account")
private EmployeeEntity employee;
Above “mappedBy” attribute declares that it is dependent on owner entity for mapping.
one-to-many association
Eg:- In any company an employee can register multiple bank accounts but one bank account will be associated with one and only one employee.many-to-many association
What is the difference between FetchType.LAZY and FetchType.EAGER in Java persistence?
EAGER = fetch the data immediately : fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.
LAZY = fetch the data when needed OR on demand: LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)
One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why?
In case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close() statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.
No comments:
Post a Comment