Hibernate & JPA Tutorial - Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hibernate jpa jql sql what the hell marco golds hi marco here in this video you're going to learn hibernate and jpa nah not really why because that would be quite the promise in fact it's going to take you months if not years of deliberate practice with hibernate and by the way sql to fully understand what you're doing so i'm not going to show you 10 000 features of hibernate you're not going to remember anyway instead i'm going to show you a couple of very important general concepts and i'm going to give you pointers along the way for your learning journey in the future sounds like fun let's go first off what problem does hibernate solve imagine you have a good old relational database doesn't matter if it's postgres mysql or what have you now imagine i have a user's database table the table comes with an id column name column birthdate column two rows inside there's two users one user is called marco the other user has the funky name ocram now at the same time in my java project i have a user class and surprisingly that user class has an id field name field birthdate field the question is how do i easily get the data from my database table and put it into user objects for example also if i have a user object on the java side how can i easily save it for example to my database table called users without having to do crazy string concatenation and that essentially is the core problem that hibernate solves among 20 000 other things now the thing is hibernate is one of the many options in the java world how to do that it is a very popular option i'm not saying it's the best option out there but in any case it helps to understand how it works so let's get it set up let's start with something very basic the dependencies you need to get hibernate up and running why is that so important because nowadays people they use for example spring boot include spring data jpa which includes like 100 libraries among them hibernate and they think well hibernate is this huge complex stack of libraries you need to include not so what you need to do is open up your pomxml file if you're using maven or your build.gradle file if you're using gradle and then paste in one tiny dependency it's the hibernate-car dependency 6.1.2 final at the time of this recording but the specific version doesn't actually matter too much then if you're using an ide like intellij load the maven changes right so the dependency gets pulled down and that's all you need to do that's it all right so we have the dependencies set up and now comes the question how do we tell hibernate to map the user class to a database table called users and how do we tell hibernate that id name and birth date should be mapped to the respective columns id name birth date in the database annotations to the rescue in fact you just have to annotate your class with hibernate specific annotations the first one being the add entity annotation identity is just a mark annotation it tells hibernate hey this class is special i want to map it to the database table that's it then by default what hibernate would do is take a user class and try and map it to a database table called user ours is called users hence we have to use another annotation table and we're just going to specify the name here table name equals users then to continue intellij already shows you hey the user should have a primary key that's right it's important for hibernate to know which field is the primary key you might have guessed correctly two more annotations for that id and there's also one which is called a generated value just quickly we have a database column id which also increments an id it's an identity column essentially and we also have to tell hibernate hey this is an identity column please don't for example generate an id yourself more on that in a second for now let's just leave it at that then hibernate is smart enough to understand well id the name should be mapped to id same with by the way a string name it's a simple type string and it maps directly to the name column so we don't need anything else just with the birthdate column i think in our database is called birth underscore date right so what we could do is we could add the add color annotation here and again give it the name of birth underscore date to map it correctly and then the usual you just need to make sure that your class has an empty constructor espec i mean if you don't have any auxiliary constructors you don't actually need that but as soon as you have an auxiliary constructor like here string name birthdate you need to at least have one empty constructor so hibernate can actually construct empty objects when it fetches data out of the database table and fill in this data it doesn't work if you just left out that constructor now because hive and i wouldn't know by default there's ways around that how to construct a user object so just make sure that in a common mistake to have other than that that's it now you might still have 20 million questions and i'm to tell you what there's a great book out there which i recommend everyone to read java persistence will hibernate it has roughly 600 700 pages and i think about 200 of them are unmapping annotations so i can't put those 200 pages into this tiny video and show you how to do many-to-one one-to-many one-to-one relationships and whatnot you'll have to work through the book you actually have to read and work through all these examples otherwise it just won't work all right so we've got the dependency we've got the mapping annotations now it's time to write some code what i did is i prepared a tiny test class which has one test method showing off the problem i've been talking about in fact i want to have a user object from my database table and i don't yet know how so what i did is i went to hibernate's getting started manual and i've copy and pasted some code and put it inside here don't worry i'm going to walk you through it because there's no way you're going to come up with that code yourself at the end what you want to have is a session factory a session factory essentially is hibernate so it's all about constructing a session factory now for that there's some funky code here with a standard service registry configure build new metadata sources registry build metadata build session factory whatever what you need to know is that this code essentially here has a look at a configuration file to configure hibernate it's called hibernate config xml it was conveniently hidden away and again when i look inside the xml file i can see there seems to be well a session factory tag and i can set a couple of properties for example i can tell the session factory hey what database do you want me to connect to i'm connecting to an h2 database so it's not my sequel or postgres in this example but it doesn't really matter so you just put your database url inside here also username password the correct driver class you need to tell hibernate when it creates sql statements what sql dialect it should use in this case h2 or mysql database it would be my mysql dialect and you can tell hibernate about stuff like hey please print out all the sql statements that you're executing but most importantly you need to tell hibernate hey i have one special class the user class hands you the mapping tag i need to hibernate hey here is my user class my user class has the special entity annotation and a couple of other annotations and now once you boot up and once the you have a look at all these classes and configuration files and you create the session factory then you can actually use hibernate to store your object into the database and also execute queries to get them out again let's see how that works all right let's start with something simple and let's try and save a user object to our database table in fact i'm going to comment out this test down here which you can fill in after having watched this video for now i'm just going to create a new test method call it save my first object to the db right and then obviously it starts with the session factory what i want to do is i want to create a new session for now a session you can think of it as just a database connection nothing else that's actually not quite true but for now that's completely fine i'm just going to wrap this with a try with resources block and here we go so the session is going to get closed again as well now what we want to do is we want to be good citizens so we always you know want to start a new transaction whenever we work with the database at the end what we're also going to do is we're going to get that transaction and commit it right and in between here is where our savings should happen and actually it's rather simple what we're going to do is we're going to call session persist right and we have to put in a user we don't have that user yet actually let me just that was a bit nonsensical what we can do up here is new user user equals new user lisa for example with a birth date of now right so we're just telling hibernate hey here please do the magic take the user object convert it to sql send it to a database table and this is just some infrastructure plumbing so far well let's try it out let's run our project let's see what happens let's see what the console says and you can see that hibernate but there's a lot of hibernate comments here in the log there is the statement insert into users id birthday name values default yes yes yes so it looks like hibernate indeed did something and when we have a look at the database table let's see right here is lisa look at that so it worked and that's essentially how you persist that means save update users to a database table you could also remove them from the database that way and now it's time to have a look at queries all right let's try and get our users out of the database again and we're going to do that with the help of hql which is hibernate's query language it's similar to sql even though sql works on database tables and hkl works on class hierarchies let's see what that means actually so i'm going to create a new test method um hql fetch users something like that i'm just going to copy and paste the code up here the plumbing so opening session begin transaction closing it again and inside here what we want to do is we're going to write session.createquery because we want to write an hql query now here goes the first parameter is your query the second parameter is the type of the result objects which are users in my case so we're just going to go with user class and now the question is what is the query going to look like very similar to sql so we're going to do select u from user u for example we want to fetch all users right now and as you can see this doesn't reference the database table it actually references the name of your entity so let's select user u right if i wanted to say for example u dot birth date i would also specify the birth date variable the birthday field not the birthdate underscore column name right so you're effectively working on your classes slash objects here not on the database tables for now i just want to cite every user right and at the end of it i'm gonna call list and that should give me a nice little list of users effectively right that that's what it looks like it looks like and now we're just gonna go through our users for every user we're just gonna go system out print and we're gonna print out the user to the console and by the way let's give our user a pretty a nicer two string method right that's it we're gonna go back here we're gonna run our hdl fetch users test let's see what actually happens again hibernate boots up which means the session factory is being constructed and when you have a look down here you can see that hibernate executed the select birthdate name id from users right and you have the user object printed out to the console pretty damn cool which means actually for you here getting a specific user shouldn't be that much of a problem what you'll have to find out is how to specify parameters inside hql queries set those parameters and then just get one user back instead of a whole list of users that again hold the whole hkl topic another 100 pages in the book i mentioned earlier on with the mapping annotations so read those pages figure out how it works fix the test down here because i can't spoon feed you everything you have to get going with hibernate yourself and build up some experience this brings us to the topic of jpa the java persistence api now what's jpa the thing is already told you there's multiple tools like hibernate eclipse link open jpa data nucleus a couple other ones and commodities at some point in the far far past got together and thought hey it would be nice to have some sort of a baseline interface jpa that all these tools need to conform to and they can add their own features if you want if they want to but in the end my code then will make sure to not use any hibernate specific classes but just jpa specific classes and i can plug in hibernate at the end and let hibernate do the saving well does that did that make sense to you if not i'm going to show you exactly what that means in code well so far we constructed a session factory down here right and we always open up sessions when you have a look at the imports you can see that sessions and session factory come from the arc.hibernate package now in jpa speak what we need instead is not a session factory but an entity manager factory right and sessions in jba speak are not called sessions but entity manager the interesting thing is that a hibernate session in fact is an entity manager hence i can simply swap out the type and a hibernate session factory already is an entity manager factory that's why this actually up here works and doesn't throw any errors so that code is already jpa filed and when you have a look at the top now these imports well for the session factory it's gone we're using the session at some other place but let's get rid of it that as well but you can see that here the two imports are now basically to the java apa interface classes let me just scroll down because there's a couple of things we need to open up to clear up it's not called open session anymore it's called create entity manager and then begin transaction has a slightly different api like session a transaction begin for example and i think this is not also closable anymore what right like so but as you can see this part already we jpa fight i'm just gonna fix the code down here and come back in a second and we're gonna continue from there all right so i clean everything up i just renamed the variables remember session is now entitymanager sessionfactory is entitymanagerfactory i just renamed the variables here in fact the code is almost the same dot list got renamed to get results list for example now in fact i'm not using hql anymore i'm using jpql the java persistence query language which is a subset of hql if you want to put it that way hql has a couple more features jpql is the standardized version so to speak but in fact the code looks pretty much the same we got rid of all the hibernate specific imports except for building our session factory here so that obviously we can't get rid of because there must be a persistence provider a so-called provider which is hybrid in that case and you just plug in hybrid you boot it up and hibernate will understand all the jpa specific annotations by the way if you paid attention in your user class for example we already all these annotations we put in earlier they are already not hibernate specific but actually jpa specific now what does that mean in practice in practice what i now could do is i could say well i'm going to replace hibernate with eclipse link tomorrow and then on friday with data nucleus it's not going to happen even though there's always some comments on reddit who claims they do it basically every day still it's good practice to basically code against the jpa annotations and the jpa api and whenever you need specific features from hibernate on top then you just use them and if you're using a framework like spring data for example the choice has already been made for you but that's all there is to jpa this brings us to hibernate's criteria api dynamic sql why is that important because imagine you have a complex form it doesn't even have to be a complex form a couple of fields depending on what drop-downs for example you select you want to generate different sql statements on the back end you can either do that by doing string concatenation with your htl queries what some people do number two is you build your own query builder framework which i've seen in almost every company i was at in the past different frameworks number three you can use hibernate's criteria api it's a bit wacky to use but it does the job now i just copy and pasted some code in here because there's no way i would have been able to write that myself i'm just going to go through that once with you we need an entity manager we need a criteria builder because we want to create a criteria query now criteria builder please let me create a query where i get users out of it user.class is the result type of the query and then you construct the query the criteria query as if it was an sql query but it looks a bit convoluted so please criteria query from my user table essentially users table i wanted to select where the column userunderscore.name we have gonna we have to talk about that in a second equals marco it is actually so difficult to even talk you through this but this is the code that it looks like and obviously if you had different conditions here you could put them into the where you have an if statement if else statement whatever you can completely dynamically configure that query that should be executed in the end now where does that user underscore come from well the thing is what i also did is to get this working i had to modify the pom xml file and i added the hibernate jpa model generator library to it and you also need the jsp runtime for it to work now what happens every time you compile your project the compiler plugin will have a look at the user class and then automatically generate on the target generated sources a user underscore helper class so you don't have to generate to reference your columns by string names but rather you have these constant these code constants you can refer to hence in our query here we didn't have to write well the name column needs to be something in fact we could just reference user underscore dot name it's type saved that way it is it as i said it does the job it's not great but again at least a hundred pages on that in the official documentation or in the persistence book enjoy all right that was a lot now let's see how we can make your life using hybrid a bit easier what essentially you want to do is what i would recommend you do is have a look at what ides can offer you like intellij ultimate for example you already saw at the beginning that when i whenever i added the mapping annotations intellij was already smart enough to tell me hey you're missing some annotation here and there but what's actually super cool is that intellij can give me auto completes automatically for for example my user here with the fields and even tell me hey there's no such field as uh birth in my user class yeah stuff like that so you don't have to you know boot up your application you will immediately see it here in your id even more so what you can do is you can select the whole thing and say run query in console specify for example your hibernate config xml file it's gonna take a tiny second but no down here you can actually see we just executed the hql against our database and we got the users back down here also super useful there's actually a gazillion of features that hibernate that intelligent offers when it comes to hibernate jpa it's just to tease you a bit here have a look at yourself how that is helpful for you or not in addition i'd recommend you to use a plugin called jpa buddy also super cool it has a ton of features i can't get into but just to get you teased again for example what you could do instead of having to write your user class yourself with all these mapping annotations what you could do is simply right click jpa entities from the database and then you have a nice little wizard which apa buddy tells you ah you want to create from the user table with these columns you want to create a class i can do that automatically for you and you don't have to worry about you know doing all this stuff manly jpa buddy can do a lot more just have a look at the website again a starting point for you to explore but just keep in mind whenever you're working with the whole jba universe make use of what ides can offer you okay i've been babbling enough about hibernation jpa let's just finish off with giving you a quick context of how this relates to you using a framework like spring boost or spring data under the hood what they do is they also have to use an entity manager factory slash session factory so what spring boot does for example for you instead of you having to use an hibernate config xml file or java persistence configuration file you can create an entity manager automatically by just putting a couple of properties inside application.properties that's it in the end spring boot will create an entity manager for you that's number one so this infrastructure plumbing number two when using spring you wouldn't use programmatic transaction code like beginning and committing transactions down here what you would do is you would use the transactional annotation right spring will make sure that the transaction is open and closed you know when the method begins when spring steps out of the method that is the second big the whole transaction management topic the third biggie is repositories because for now we have to write these strings here blah blah blah and what spring data offers you specifically is these repositories by the way that's just pseudo code so you would simply write interface user repository and have a method find by name and maybe even give it a name um parameter and you will get a list of users back now what spring data does is it will automatically turn all of this into the appropriate hibernate slash jpa code for you you don't have to worry about writing the see at the sql and whatnot it's just a huge help a huge boost for your productivity hopefully but that's the three big thing is infrastructure transaction stuff repositories and i guess a couple more things which i just forgot all right that's it i hope you found it useful now go buy that book read the 700 pages work through them come back in two years well actually before the let me know how you found the video in the comments subscribe and thanks for watching sayonara
Info
Channel: Marco Codes
Views: 90,060
Rating: undefined out of 5
Keywords: jpa, jpa tutorial, hibernate tutorial, hibernate java
Id: xHminZ9Dxm4
Channel Id: undefined
Length: 24min 27sec (1467 seconds)
Published: Tue Aug 23 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.