HIBERBATE Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. It is a java framework that is used to develop persistence logic. Persistence logic means storing and processing the data for long use
HIBERNATE FRAMEWORK Hibernate is a Java framework that simplifies the development of Java application to interact with the database . It is an open source , ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.
Diagram view
1) ORM Tool An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the database. Basically convert object into row in db table & vice-versa.
Picture View
2)JPA JPA is just a specification that facilitates object-relational mapping to manage relational data in Java applications. In simple terms,JPA is a standard given by oracle which basically what steps you can follow to save a object to database but hibernate implements that steps. It provide two interface : EntityManagerFactory EntityManager ->Provide CRUD Operations
How to use Hibernate in Spring-boot In order to use hibernate in springboot we have to follow two steps : Add dependency to pom.xml file Extends the JpaRepository < EntityName,PrimaryKey > into repo file.
Hibernate Annotation
Commonly Used Annotation @ Entity : This class is identified as an entity by this annotation. @Table : The table name where the data for this entity is to be stored is specified in this annotation. Hibernate will automatically use the class name as the table name if the @Table annotation is not used. @Id : The entity's identifier is marked by this annotation. @Column : This annotation describes the Column's specifics for this field or attribute. Property name will be applied as the column name by default if the @Column annotation is not given. The most common attributes of the column annotation are the Column's name, Column Length(Size), the Nullable value, and the Unique Value of the Column. @ GeneratedValue : This annotation help to auto assign the primary key a value.
Fetch Types in Hibernate EAGER Load the associated data of the other entity, beforehand which is bit costly . LAZY Load the associated data of the other entity, only when requested. This is done on demand.
In more details …..........
Points … In EAGER , when we fetch the Questions at that time, Answer will also get loaded. In LAZY , when we fetch the Questions at that times, Answer will not fetch, it will load when we called the getter method like , q2.getAnswer().
Cascade Types in Hibernate In Hibernate, Cascade Types mean how the data should be kept between the two related entities. There are set of pre defined types. CascadeType.PERSIST : Both save() or persist() operations cascade to related entities. CascadeType.MERGE : Related entities are updated when the ownership entity is merged. CascadeType.REMOVE : Removes all related entities association with this setting when the ownership entity is deleted. CascadeType.DETACH : Detaches all related entities if a “manual detach” occurs. CascadeType.ALL : All of the above cascade operations.
CascadeType.MERGE CascadeType.MERGE is a cascading type in Hibernate that specifies that the update (or merge) operation should be cascaded from the parent entity to the child entities . For example, consider a scenario where you have a Customer entity with a one-to-many relationship to Order entities. By using CascadeType.MERGE , any changes made to a detached Customer entity (such as changes made in a different session or transaction) will be automatically merged with its associated Order entities when the Customer entity is merged back into the persistence context.
CascadeType.REFRESH CascadeType.REFRESH is a cascading type in Hibernate that specifies that the refresh operation should be cascaded from the parent entity to the child entities. When CascadeType.REFRESH is used, any child entities associated with a parent entity will be automatically refreshed when the parent entity is refreshed. This means that the latest state of the child entities will be loaded from the database and any changes made to the child entities will be discarded.
CascadeType.ALL It a cascading type in Hibernate that specifies that all state transitions (create, update, delete, and refresh) should be cascaded from the parent entity to the child entities. @Entity public class Questions { @Id @ GeneratedValue (strategy = GenerationType.AUTO ) private int id; private String question; @ OneToOne (cascade = CascadeType.ALL ) private Answer answer ; } @Entity public class Answer { @Id @ GeneratedValue (strategy = GenerationType.AUTO ) private int id; private String answers; }
In more details.. If we don’t use cascade type then it will not save the data into the database for associated entities. In order to handle this , if we use cascadeType.ALL it will internally save that record into database too.
@ OneToOne Mapping One to one represents that a single entity is associated with a single instance of the other entity. An instance of a source entity can be at most mapped to one instance of the target entity. We have a lot of examples around us that demonstrate this one-to-one mapping . One person has one passport, a passport is associated with a single person . One Question has one Answer, a answer is associated with a single question.
Understand with example…. Type of one to one mapping… I n database management systems one-to-one mapping is of two types- One-to-one unidirectional One-to-one bidirectional
One-to-one unidirectional In this type of mapping one entity has a property or a column that references to a property or a column in the target entity. Let us see this with the help of an example- -> consider the example of Question and Answer Table .
C ode example… There is two classes,Questions and Answer.
Explanation…… In this example Question T able to associated with the Answer Table with the help of a foreign key ( answer_table_id ) which references answer.id . The target entity Answer does not have a way to associate with the Questions Table but the Questions T able can access the Answer Table with the help of a foreign key . Note)Demonstration using Database :
One-to-one bidirectional Until now the relationship was unidirectional i.e. we could access Answer from the Question entity but not vice-versa, but why would we want to have a bidirectional relationship, and what is the problem with a unidirectional relationship?
Problem… 1) I f we want to access Question entity using Answer entity ,it will be not possible to access. 2)If we save the Answer Object explicitly ,the related Question Object will not be saved.
Solution …. Code Example..
Explanation.. Now we don’t have a column referencing to Question table in our answer table so what is this piece of code ? This is where Hibernate comes into helping us, mappedBy = “ answer ” tells Hibernate to look for a field named answer in the Question class and link that particular instance to the current student object. Now that we have understood the linkage let’s try to add an entry into the database, but this time we will save the answer object explicitly which will implicitly also save the related Question object because of CascadeType.ALL .
Code Demonstration… 1) Insert a Object into database 2)Retrieve and display
2) @One-to-Many Mapping Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence api ) is like an interface and the hibernate is the implementation of the methods of the interface Like how insertion will be down is already defined with the help of hibernating. Let’ understand the One to many mapping with the help of a real-life example. Bike manufacture can manufacture multiple models of the bike but the same bike model cannot be manufactured by multiple manufactures.
For Understanding Purpose
Code Example…
Manufactures Class…
Model Class ...
Points The @ ManyToOne annotation lets us create bidirectional relationships too. In Manufactures Class, mappedBy = “ ob ” tells Hibernate to look for a field named ob in the Model class and link that particular instance to the current Manufacture object .
3) @ ManyToMany Mapping
Situation Discussion A Employee can work in multiple Projects & A Project can be assigned to multiple Employee . In @ ManyToMany for entities mapping a “3 rd Table” is always created. Now let’s discuss through the last picture !
Employee Class
Project Class
Merged
More Points…. We also use mappedBy in one entites so that only one extra tables created. Here in code we write mappedBy =“projects” in project class and will tell employee class you don’t need to create table,project class will take care of.