Hibernate Interview Questions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hal they're welcome to this video on hibernate interview questions you can find the hibernate link on our website in as part of the frameworks tab hibernate and you can look at all the questions which are really there let's go into the different questions which are which would discuss as part of this set of videos first is why hibernate I mean we will start off with JP what is Java persistence API how is it related to hibernate and why you should use hibernate if we look at a basic architecture of hibernate and we look at things like pagination a schema generation how do you map an entity I mean how do you create identifiers and how do you really map inheritance hierarchy with hibernate so those are the different things that we would look at with hive with respect to hibernate and JPA so let's get started so we'll start off with JP a what is JP and how is hibernate really related to JP a so when we talk in terms of Java we talk in terms of objects I mean we talk in terms of domain models and when we talk about databases we talk in terms of relational tables so how do we really map a java object to a database table earlier we used to do a lot of queries so we used to write queries to get the data from the database and we write kind of a result mappers row mappers and a lot of stuff to map it to the java objects this was a very tiresome cumbersome project and I mean product process and also it was very error-prone because you kind of write a lot of boilerplate code to do a Adam mapping and that's where or JPA that's where hibernate came in hibernate said come on I'm Alec I'll be able to help you map easily the Java objects to your database and once hibernate became popular JE came with came up with the specification called JPA so what Java like JP a was made part of Java persistence API was made part of the Java EE specification and it kind of defines how a particular object can be mapped to the database so it defines like it J becomes kind of the API of how you can map a particular object with something in the database and later hibernate supported JPA I mean hibernate started implementing whatever interface was defined by the JPA so enough hibernate is really a first-class implementation of the JV JPA so JP is basically a specification of how do you map something and hibernate really implements that mapping so JP is the interface and hibernate is really the implementation of that particular interface probably that's the best way really to look at it JP is actually a specification and hibernate is an implementation of that particular specification the great thing about using JP a is let's say tomorrow two years down the line you see that hibernate there is nobody maintaining hibernate I am in hibernate let's say is fallen out of like having support good support and you want to switch to another framework if we are using JPA then it's possible if any other framework also implements the interface which is defined the specification which is defined by JP a we can easily switch it it would just be the matter of switching a hibernate jar with that particular jar at least theoretically so this is the benefit that JP a offers and V in this example in this particular video in this particular interview questions section we will look at directly the hibernate things most of these things which we use in this particular video are JP a compliant so the annotations might be a hibernate most probably they are JP a annotations so let's get started as we discussed earlier what is hibernate it's basically an ORM framework it helps us to map Java objects to database to databases and it helps programmer because you don't need to worry about how to query something from the database hibernate takes care once you do the mapping hibernate takes care of updating deleting inserting something in everything hibernate takes care of it provides simple syntax on how to do it so now actually I would I should say JPA takes care of it so once you follow the JPA specifications and do the problem mapping then hibernates helps you to implement that particular stuff so how does hibernate really work hibernate like if you look at hibernate you have the application and you have the database and really the hibernate fits in between all of them so hibernate is the layer between your transient your objects which are going to be stored to the database that's the persistent objects and the database themselves so hibernate kinds of defines the mapping between the persistence objects and the database we create a lot of mapping files between the persistent object and the database and session factory is just a cache of it I mean all the mapping files are loaded and they are available in the session factories cache session is basically something which kinds of represents a conversation between the application and the database let's say user click something update a particular user I mean user clicks update account on the screen so you need to take the account details and you need to update it to the database so the details first come from the screen to the persistent objects once they come to the persistent object a session is created a hibernate session is created and during the hibernate session the persistent objects map click the appropriate queries are run to update the database with those particular things like the this session is needed so that whatever values are there in the assistant objects are transferred to the database the most important thing is this session is per request or it something of that kind the next important thing is hibernate also allows you to have transactions so JTA java transfers transaction api hibernate supports that so basically transactions are very important because let's say there is a failure in between let's say there are five steps in doing something and the third step fail we want the first two steps which were done to be cancelled otherwise the system would be in a inconsistent state so that's where the transaction management comes into picture and hibernate really has a good support for her transaction management as well in your screen right now is really a small entity called table I mean called person which is mapped to another table called table person so here we are taking a class called person and we are mapping it to a table called table person we are also saying there's a unique constraint the unique constraint is person ID I mean the ID should be unique so we are defining the unique constraint as well on it we are saying this thing maps to a column name name and this particular ID maps to a column named ID so this is basically the way you define the mapping between a class the classless person I mean that's basically when we looked at the picture the person is a persistent object that's the object we want to store to the database and a table is part of the database so we are mapping a persistent object with the table inside the database and we are defining the mapping to it so that basically a sample example of how you can map or entity to some database in hibernate in a lick of hibernate there is a at immutable annotation this empty Muta annotation is helpful if you define it on the table if I define it here then it means this table content will not be updated I mean this the content of this particular object will not be updated so you don't need to really take this content and store it in the database it would be only some kind of read-only data data it will never be updated it helps hibernate kind of do a certain amount of performance improvements so the next important thing is how do you define unique identifiers most important thing in a relational table is how do you uniquely identify a row in the table and when you insert a new row into a table how do you really generate a unique identifier that's one of the quite tricky questions when it comes to databases a lot of times we use sequences I mean in databases I mean in old times with Oracle I was creating hundreds of sequences a sequence for every table which is there and we used a sequence to generate the ID with hibernate also we have support for sequence you can use a sequence as well I mean you can say I want to use a sequence from the database so I can say I want to use this strategy of generating from a sequence and the name of the sequence is this so that's an option the other options are something called an identity this is only supported in this particular databases the one option is for you to write your own logic I mean you can define a custom generator which kinds of you want to talk to a database you can talk to it and get and generate an ID you right can write a lot of logic there or you can put it to auto then hibernate decides what is the best way to generate the ID and it would give it to you so these are the different ways which are possible to generate an identifier in hibernate what is optimistic locking it's a very very very important question I mean especially when you talk about transaction management if there are a lot of parallel transactions running you don't want to hold a lock for a long time if you hold a lock for a long time then the other tables cannot acts and other queries cannot access the table other transactions cannot access this table and it would mean that the application would slow down a lot so how do you improve the performance of the application that's where the optimistic locking comes into picture so we like optimistic locking is like you don't really hold a date a lock to the table you just have a cache of what was the old value and when you are trying to update the column you check whether the old value is same as the current value if the old value is not really the same as the value in the database then it means somebody else has updated the value in the meanwhile then it means there's a error so I mean that is something which needs to be handled but what it L I mean what optimistic locking allows is that there would not be a lock on the table so all the other transactions can go ahead and access the data from this particular table and the performance of the application will be better so hibernate actually provides two approaches to optimistic locking either I can use a version number or a timestamp so you can like using the version number is really the best approach for using I mean best approach to use with hibernate it's impelling D you can use the @ version annotation so you are defining this is the column and this is the column which is very important whenever something gets updated in here this column also gets updated so you just check whether this particular value is the same as what it was when I read this particular row if it's the same then it means that the row has not changed if it's different then it means that some update has happened in the in the intermediate stage and so whatever data I'm trying to update will lead to a none consistent update so that's basically optimistic locking and let's have you do it in hibernate the next important thing is mapping a hierarchy of classes to hibernate let's say there are let's take this example is car and the Formula One car extends car so you have two classes one is car and the other one is Formula One car which extends car so there are multiple ways how I can map this kind of a structure to a database I mean in the database I can have two different tables for each one of these or I can store these values in the same table so the first strategy which we are going to discuss is how we can store both these classes I mean how we can map both these classes to the same database table so that's the first thing that we would discuss so that's where we use the strategy called inheritance type called single table this is called single table per class hierarchy so this is called single table per class hierarchy so there's a hierarchy of classes car for Mila one car and I am using only single table to represent these two classes in the database so how do you define that is by using a strategy called inheritance type dot single table that's what you say and then you would create a discriminatory column so you would say discriminated column is the car type so the car type what would be the value would be the discriminated type is string so the value for this car type I mean the type of this car is string and here you are defining one when I am creating on the car I am putting the value for the discriminator car it's car this is Formula One so what happens is when I try to store car to the database then the field car type will have a value of car if I try and store Formula One car to the database then the field in the database car type would have a value of Formula one this is how you can map a single table per class hierarchy so this is how you class a hierarchy of classes to the same table in hibernate the next important and the next the other way of implementing the same thing is to use table per class so you kind of decide that I would not want to have the data related to these two things I would want car to be in a separate table and Formula One car to be in a separate table then it's kind of the default I mean this is how we map things right I mean if even if there is no inheritance hierarchy I can really map these two things to two different class at two different tables so I mean Here I am putting a annotation saying inheritance table per class but it's not really needed because that's basically the default so next question is how to map a one-to-many unidirectional relationship so I want to create a one-to-many unidirectional unidirectional is one direction only so you want a relationship between the parent to the child but you don't need a link back from the child to the parent that's basically a unidirectional relationship so one-to-many is kind of a parent-child relationship there's one parent and they can be multiple children's so oops not really davin it's maybe like a parent object and a child object so you can have multiple child's for the single parent object let us think that way so this parent can have multiple child so the way you say that is by specifying an annotation called one-to-many so here I am saying at one-to-many and I am defining a set of this child object so this actually represents one to many unidirectional relationship it's a unidirectional relationship bit because I don't specify anything in the child child doesn't really know anything about the parent it doesn't have any field which relates to the parent and if I have a connection back to the parent so here I am saying a child there's a many to one relationship to a parent and this is called a bi-directional relationship I not only have a relationship from the parent to child but also there is a relationship between the child to the parent so there is a link back from the child to the parent that's at many to one this is how you define a one-to-many bi-directional relationship with hibernate actually this is exactly how you even define all of these with APA as well so whatever annotations which we are looking at are the jpoa annotations as well so it like it doesn't really make a difference whether you're using Eric it's always preferred to use a JPA annotation over a hibernate annotation because with the JPA annotation you can switch to other ORM frameworks as we discussed earlier the next important question is how do you implement pagination with hibernate the pagination you can implement with hibernate by setting something called Max results on the queries you can say I want to get only ten results back I want to get only 100 results back I want to get only thousand results back so then the hibernate would return only those number of queries back and also you can set the first result so you can say from this particular result from 500 throw I need thousand rows or from 50th row I need 20 rows so you can say first result 50 and I can set max results 20 so that's how you return a set of electronic queries something usually it returns all the results of that particular query if I want to limit the number of results you can use pagination lazy and Association what is lazy association in hibernate the classes are directly mapped to each other for example a parent is directly mapped to a child so whenever I load the parent if I start loading the child as well then there is a performance impact it might be necessary it might not be necessary to have that performance impact so in cases where you don't really want to load all the children when a parent is loaded you kind of make the Association lazy so you do this is kind of the default configuration in hibernate so when you load the parent all the many-to-one I mean one too many associations will not be loaded they will be lazily loaded in the sense when they are called they would be loaded but by default they would not be loaded this is called lay the Association next we will talk about one important performance problem in hibernate that's called the n plus 1 selects problem or D I mean the thing is let's say there is a parent and there are there are a 10 child rows so there is one parent row and there are 10 child rows by default if you leave the configuration as default hibernate would use 11 queries one for the parent and 10 for each of the children to get all the data and this is highly inefficient so it's preferred not to use select and use something called join so this join would prevent this n plus one selects problem it would make sure that all the children are returned in one query all the data related to all the children's is fetched in a single query rather than using ten different queries to retrieve details of each child so that's I mean the two things lazy Association and n plus one selects problem our kind of most typical problems that you face with performance related to hibernate so you should be very cautious with performance when you are talking about Oh RM framework because in the background you should understand what's happening with the ORM framework in the background what hibernate doing the background what's the specification of JPA saying you should understand that and make use of the appropriate mapping to make sure that the appropriate things are really happening on the back end if like when I started with hibernate I mean it was a great deal of learning to understand how the mappings work what happened it does it in the back what hibernate does in the back end a lot of things would not be really clear especially when you are new to hibernate and you see how easy it is to map you start doing a lot of things and later there is a performance impact of it and then you go and look at the back end and you see you have done something really silly so that's quite common but you should be very the cautious when you use JPM mapping and make sure that there is not really any lot of performance impact because of using a JPA next we will look at a schema generation so basically once I map a Java object to a table in in the hbm's or directly using annotations in the class itself I can use that information to generate the entire schema of the database the tool which helps us to do that is called schema export this schema export has a lot of features it can I mean it can just look at the beam definitions the annotations which are dáil in there and it can generate the entire database table structure with relationships in there as well and also there is an additional feature where it can generate incremental updates as well so it's it's it's really useful tool also there are tools available to the reverse you can give us kheema and the tool can generate the hibernate mappings for you so it can create the entire beans with mappings defined in HTM or if you want even annotations defined in the beam class itself that kind of things are possible but be really cautious as we talked about earlier performance the default mapping some times are not really performance efficient I mean they are not really efficient so you need to understand them like even though you are generating them just take a look at them and make sure that you are making the right choices regarding the mappings so the next thing is kima validator I mean scheme of a little tool is really a very important thing like lot of times there is a mismatch between what you define in the hibernate mapping and what's really in the database so if I define a specific table name in the hibernate mapping but that table doesn't exist that's a like that's basically not matching the structure of the database does not match the mapping let us say there is a dissing column or the column name there is a typo I mean all these are situations where there is a out-of-sync I mean where the database and the mapping is out of sync so a schema validator helps us to find this kind of things so schema validator is a very useful tool for this kind of stuff next we would look at some of the hibernate best practices what are the hibernate best practices the first thing is have a natural key I mean identify a proper identifier avoid using a sequence generator to create an identifier as much as possible try and use natural keys I mean SSN for example is a natural key so use natural keys as much as possible the second one is if you're using hbm's then put each map each classes mapping in a separate HBM file don't have a single large HTM file with mapping for 50 tables imagine 10 developers working on that particular file it would be a mess so make sure that you use each class mapping in its own file also the using queries with hibernate is not really recommended but in certain situations where performance is really critical you would go for queries and when you go for queries try and externalize these queries so try and put these X queries in a property file or in an XML so that they can easily be changed at a later point in time this makes the applications more portable also all the time when you go for SQL use bind variables never use direct SQL queries because like it's it's kind of a security flaw I mean if you directly use string concatenation to generate SQL queries then there's a chance that SQL injection can happen so to avoid it always use bind variables never concatenate and generate the queries yeah as I said earlier try and use hand coded JDBC as much as possible I mean using SQL completely defeats the purpose of using hibernate so unless is a performance critical requirement don't use hand coded SQL and also I mean this is kind of the default use all lazy association for lazy fetching for associations so that's really the default so also like make sure that you're only using lazy fetching and you would disable the eager fetching in a lot of places and always use bi-directional relationships have the relationship from the parent to G child and child to the parent so that it's easy whenever you have a child to get to the parent or whenever you are at the parent to get to the child and the last one I would want to leave you is try and understand the n placements LX problem and try and avoid it all the time so n plus one selects problem is kind of the most common performance problem with hibernate try and avoid it understand it probably do an example and try and understand it and try and avoid it as much as possible so there you go those are all that I would want to talk about regarding hibernate these are all we looked at a varied range of aspects regarding hibernate we started with how to map a single file and we started with what is JPA how hibernate is related to JPA and then we saw how to map an entity how to map a hierarchy of classes to tables then we looked at different tools which hibernate of our schema validator schema generator and all that kind of stuff and we ended up discussing the hibernate best practices so there you go that's all I have to share and have a nice day bye
Info
Channel: in28minutes Cloud, DevOps and Microservices
Views: 203,780
Rating: undefined out of 5
Keywords: java interview questions and answers, interview, in28minutes, Hibernate (Software), Ranga, rithus, Rao, in28minutes tutorial, hibernate interview questions, Karanam, java, hibernate interview questions and answers for experienced, java interview questions, Hibernate Interview Questions
Id: nb4kKVDc4cE
Channel Id: undefined
Length: 28min 14sec (1694 seconds)
Published: Sat Jun 20 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.