Learn Hibernate Java Framework the Easy way! | Karthikeya T | Skillshare

Learn Hibernate Java Framework the Easy way!

Karthikeya T, For Your Learning Needs

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
52 Lessons (5h 4m)
    • 1. Must Watch!

      1:42
    • 2. Introduction

      4:28
    • 3. Importing Maven Project

      0:35
    • 4. 01Introduction And Terminologies

      6:40
    • 5. 01JDBC vs Hibernate

      5:48
    • 6. 02Things You Need

      4:29
    • 7. 02First Hibernate App Part 1

      10:55
    • 8. 02First Hibernate App Part 2

      7:40
    • 9. 02Exploring The Main Logic

      7:18
    • 10. 02Improving Our Code

      4:27
    • 11. 02Incorporating Annotations

      6:44
    • 12. 02Hibernate Auto Sync

      4:33
    • 13. 0301GeneratorClasses

      11:01
    • 14. 0302CustomGenerator

      5:25
    • 15. 0401CRUDAppIntro

      5:12
    • 16. 0402ExploringDAO

      5:37
    • 17. 0403TheMainClassAndRunningOurApp

      4:11
    • 18. 0502SaveAndPersist

      5:15
    • 19. 0503CloseAndEvict

      4:13
    • 20. 0504OtherMethod

      3:59
    • 21. 0601OneToOne

      10:48
    • 22. 0602Cascading

      10:56
    • 23. 0603OnetoMany

      9:51
    • 24. 0604ManyToOne

      6:26
    • 25. 0605bidirectionalMapping

      3:39
    • 26. 0606ManyToMany

      5:46
    • 27. 0607OrphanedRemoval

      3:10
    • 28. 0701FetchStrategies

      8:14
    • 29. 0801ListAndSetMaping

      4:39
    • 30. 0802MappingMap

      2:34
    • 31. 0803EmbbededType

      2:33
    • 32. 0901MappedEntity

      4:05
    • 33. 0902SingleTableInheritance

      4:38
    • 34. 0903InheritanceTypeJoined

      3:23
    • 35. 0904TablePerClass

      2:17
    • 36. 0905GoodPractices

      5:05
    • 37. 1002FirstLevelCacheExample

      6:11
    • 38. 1003SecondLevelCacheAndEHCacheConfig

      7:22
    • 39. 1004EhcacheExampleProgram

      4:06
    • 40. 1005ConcurrencyStrategies

      5:42
    • 41. 1006NoteworthyPoints

      3:40
    • 42. 1101HQL

      7:35
    • 43. 1102HCQL

      13:02
    • 44. 1103NamedQueries

      4:02
    • 45. 1201Transactions

      8:11
    • 46. 1202Versioning

      9:01
    • 47. 1203ConnectionPooling

      7:18
    • 48. 1301BulkInsert

      4:59
    • 49. 1303ScrollableResults

      3:43
    • 50. 1401ReverseEngineeringPart1

      7:21
    • 51. 1402ReverseEngineeringPart2

      8:07
    • 52. 1501EntityManager

      4:58

About This Class

Hibernate is the most popular ORM tool for enterprise Java Applications. In this course you will Learn the core concepts of Hibernate ORM Framework

  • With hibernate, you will know how to map some of the OOP notions like inheritance, polymorphism, composition, Java collections etc, with Relational Database tables.

  • You will learn some interesting core concepts of Hibernate, like Lazy loading, caching, fetching strategies, optimistic locking, connection pooling, seconds level cache etc.

  • You will learn how to do reverse engineering so that you can generate POJO entities from an existing database.

  • And many more interesting concepts

  • Downloadable examples in each chapter

Transcripts

1. Must Watch!: full stack developer sort in great demand and are paid very high. So it's not enough that you'll on one technology but rather full stack off technologies. We have all the courses on sculpture that would help you become a full staff Java developer so that you will gain skills to develop, end, to end applications from scratch all by yourself and be eligible for top profile jobs or to work on freelance projects. So was it this link? Its corporate dot com slash skill share. It has all the links to our courses, and they're all organized in a proper sequence. You can start from Java programming, and here's a link to that course. Once you complete this course, you can get into advance Java. And here's the course link for the same. Like was, you keep going and complete the entire stack off technologies. The courses were also include creating into and applications from scratch. And if you're struck anywhere, you can always post your questions. Even if you're inexperienced. Dollop er I would highly recommend you to start from scratch because many people who followed this approach and gone through all these courses from scratch have seen very good results. Many individuals have clear interviews. Some of them also cleared certification exams and some of them also got into good jobs with better income and all. So I would highly recommend that you followed this approach. Start from Java programming all the way to all the advanced courses. Hope it makes sense. 2. Introduction: welcome to my course on hibernate. Having it is the most popular open source object, relational mapping framework or simply Orem framework that will is, have you interact with the database from your application As a job a developer. You will feel very comfortable using habit meat because it will enable you to interact with the database in object oriented manner than writing static queries like you normally do in case off Jerry BC. And there are a host off benefits associated with using harmonic framework compact to using Jerry BC Some of them are. You will be able to use some notions like inheritance, polymorphism composition, Java collections, etcetera. And then you would be able to map these terms with the relation thereof s tables. You will understand about it in this course. Having it offers better performance with the futures like lazy loading, cashing mechanism, fetching strategies, etcetera. We're going to talk about all of them in the scores. Harbin. It offers better transaction management and with the features like optimistic locking data , consistency is insured. Have been It is extensible as well, and in fact we're going to take a look at how we can use third party libraries to introduce some of the features like connection pulling second level cache A etcetera. And there are a host of other concepts with all cover in this course. For this course, I'm assuming that you already know how to write Java programs and run them. You also need to be ever off some basic terabytes and ask your terminologies along with some knowledge on how to use them and Justin gets. If you don't know any of these, then I have an excellent course on the same as well. You can check it out or drop me a message, and then I'll be able to get back. Typically, an application would follow the following layered architecture er, and this course is primarily focused on how happen it talked to a database from your application logic. If you want to learn about just off the technologies that fall in other layers, or if you want to learn how the entire application is built, you can check my other courses. O R. If you need guidance on where to get started and what to learn, you can drop me a message, and I'll be happy to respond. Why take my course, I have the unique ability to teach the concepts and simple and easy to understand manner. You can check the free preview videos off the scores and you can take the call. No pressure. I tried my best to keep these videos very focused and to the point, because time is very precious and I respect your time. Here are some of the benefits In taking my course you will gain confidence and stand on your own. If you've been using java for a while, then you must know how been made. There is literally no high in job application that goes without using have been made. My primary goal is to make you comfortable using have been eight and stand on your own. If you don't have proper foundation on the technology, you will simply end up wasting a lot of time and energy in your workspace without making any progress. This course will give you a good foundation on the technology and will make your product to now. Did you ever come across with the colleague who tries to be smart, as if he knows everything in the world? Well, you can keep him come by making a meaningful arguments with him on the subject. Give a lot to be comfortable in giving or taking interviews on the subject. If you enroll for this course, you will have lifetime access to my course, which means you can watch the videos in your free time. You don't have any pressure to complete the course within a certain time. If you enroll for my course, you're also eligible for free updates forever. So I'm sure that you're interested in learning habit need and you have come to the right place. I will definitely save your time, energy and frustration because I've done all the hard work for you. I created a lot of examples that you can download and all you need to do is to learn from my experience and save your precious time. So I would be really happy to see you in my course. I will see you soon 3. Importing Maven Project: 4. 01Introduction And Terminologies: in this video will try to get some quick understanding on have Been it framework and a few other terminologies that you should be aware off before we dive into our first example. First, let's try to understand the term framework you can think off framework as an enrollment are set off libraries that together will help you address a particular set off related problems . I mean, think about any framework out there We have logged for the framework to a does a problem off logging, thereby will be able to trace the application errors efficiently by taking a look at all the log messages. And we have maybe in which acts like a framework or as an enrollment on which we can run our made in plug ins, and this plug INS will actually perform the project. Management tasks similarly, have been. It is also a framework and is there to address a particular set off related problems. And those problems are obviously associated with database. We're going to take a look at the difference between dealing with the database in traditional approach, where since I been eight and then you'll see the difference obviously have been, it is going to be a better option will see wine in a while. And here are some of the advantages by using the framework, and these are quite obvious. Print books would save a lot off project development time because you don't have to write all on your own what a framework is already doing. Insurrection. Just download the framework and use those libraries that would save a lot of typing, and it will also increase the aural productivity off the project. We just quite obvious, and framework will help you write clean code. You can accomplish the same task with less a number of lines off God, and at the same time you're court looks more readable, etcetera, and then we have autumn or object relational mapping tools. These tools help you map the Java objects with demolition database tables. I mean, if you take a look at a job object, you have an object called Student within which we have all these properties. I did name an email we consort off Magda seem with the relation that the best table we have , student table and its attributes. I d name an email. So this is a kind of problem that these autumn tools are going to solve. And here are some of the examples off or them tools. One is have been it, which this course is about. A clip link is another example of the same. If you take a look at how we deal with database using J BBC, we start off, create our database specific query, and then isn't the execute query off the statement. Object will be able to get back, the results said. And then we have to manually take care off, looping through all the results and assigning those results into an object like student. And then we're also adding each off the student object into the students list. Well, all this can be done automatically when you use an autumn to like hibernate. So that's going to save a lot off time and the host off of the benefit and what? The real reason why we want toe use an Orem tool is it would help you get it off some of the discrepancies associated with we trying to map the Java objects with relation database tables, for example, not all data types that are supported in Java or supported in database so tools like Cabinet are actually going to solve the problem, and it would enable the developers to interact with the Java objects while happen. It is actually taken care off mapping those objects with the relational database tables and is going to perform all the database operations. So these autumn tools are going to provide that kind of an abstraction for dollar purse so that they more or less interact with the Java objects, but not with the database. Java persistence API is simply a specification whose implementation is actually provided by these Orem tools, and having it is one off them. So at let up one of time. If you try to switch to a different all the NATO or a different or um, tool, then you have the flexibility because all these frameworks will actually implement the same specifications, which is Java persistence. FBI specification. And here's a Cabinet definition, and you'll be able to understand on your own having it is simply an open source or I'm tool from Red Hat. And that is basically a framework that provides implementation for Java. Persistence, FBI and the major role off hibernate is to map the relational database tables with the job objects. Here is the high level architecture off. Dealing with the database isn't a traditional approach. I mean, isn't very busy. So we have our job application inside which we're going to use the jetty busy FBI to start off, interact with the multiple data basis by using the driver manager. And these drivers that are specific to database will actually implement all these AP ah specifications so that we can interact with the database coming toe have innate having it is actually going to take care off all that headache, and we actually interact with the Cabinet framework and then have been it. Framework will deal with all these technologies like Jdb Siege our database connectivity, and J. And I were going to talk about J N D. I Jabba naming and directory interface when we talk about the connection pulling etcetera and it would also use the Java transaction. FBI to perform the transactions were going to take a look at examples off transactions as well. So this is the high level architecture off hibernate now. This is not the exclusive architecture. There are few of the components that are in mold in this architecture, but I'm not going to present them right now. For obvious reasons, you're not yet ever off. Some of the concepts involved in have been it. But I will definitely revisit the Harbin IT architecture and would let you know the other components that are involved in this architecture. So for the time being, this is This is what happened in architecture would look like at a very high level. All right, let's continue from next video. 5. 01JDBC vs Hibernate: Here are some of the differences between J. BBC versus Happen it and you'll see why have been it is a better alternative combat to jail . BBC One is off course, the object mapping, which we've already talked about with Jerry busy, we have to do it manually and with have been it, it will do the same for us. One of the primary strengths off happen. It is it offer so called I have iniquity language. Now. If you worked with database for a bit, then you probably know that the syntax off SQL statements vary a little bit, depending on the database that you deal with, if you learn, have been it query language. No matter which did the best you're using, the statements are going to remain same so that it would be easier to switch to alternate data basis without having to change or without having to introduce a lot of changes in your code. Using Jerry BC, you sort of have to enter the database specific queries, but with Cabinet EQ and just simply use hedge fuel that would remain common for all the databases because because happen, it is actually going to take care off converting this into the database specific SQL statement. And added to that, as I've already mentioned with have been it, you're actually interact with the Java objects. So in here, in the statement with which we're trying to delete an entry from student, this student in here is actually the name of the class, not the name of the table reciting the relational database. So that's the kind of beauty that happen. It offers for developers. And all the Java developers would actually feel more comfortable interacting with the job object rather than the relation database table. And as a by product, we have the falling advantages. With this approach, we can actually get into the notion off polymorphism inheritance, etcetera and have been It will take care off mapping all these notions with the relation database. We're going to take a look at an example. We have videos dedicated to talk on all these. You'll have to wait until then and the statements that you write in happen it or not case since two, for example, hammocks off upper case and lower case in here, but still it is valid. But of course, case sensitivity is applicable when you're defining your class name. This is something that revolve that you talked about isn't HBO? You don't have to worry too much about switching to alternators. One of the major advantages off use inhabited framework is its ability to handle the exceptions. I mean to go back here with very busy approach. We have to rob the code and on the try catch block, and then we have to cast the exceptions. That's because these are checked exceptions, and and we developers have to take care off dealing with those exceptions. But whereas with hibernate happen, it is actually going to convert those checked exceptions into unchecked exceptions so that we developers don't have to deal with it. So that's going to save a lot off typing, improve the readability of the code, etcetera. And having it is actually going to incorporate certain mechanisms, like cashing mechanism to improve the performance, thereby it will try its best to keep the database requests at minimal level possible. Also, there was some kind off a database connection, which was all that existing from previous initialization then have been It will try to use that connection instead of creating a brand new connection again and again. So aspects like these would help us improve the overall performance off the application and have been, It allows us to write annotations. These are basically GP annotations, and the advantages associated with annotations are quite obvious. You can get it off all the XML configuration files. It's also like your writing court in more natural passion. Get it off lot off mess by using annotations. And finally, one of the greatest strengths off have been eight is that it's ability is that its ability to adopt is, is that its ability to adopt a new changes introduced in the database. For example, with Jerry BC If you're trying to add a new column in the database, then you have to go and change the court in here, for instance, in here we have toe add another statement to deal with that column, and even in the cord, that helps in adding an entry into the database. We have to introduce another statement to deal with that new column. Oro. It is we developers who have to take care off those new changes, but whereas with happen it happened, it will help us get it off all that burden and it is going to do the job for us. Now we have a host of other benefits off hibernate. Worse is dealing with the database in traditional approach. But I'm not going to list them because because you're not yet aware off some of the habitants concepts, and they would not make a lot of sense. Well, we're going to talk about all those concepts in detail. Sell state June for that. And of course, we can get it off some of these problems with Jerry BC, as well by introducing new class files, etcetera. But it would be as good as introducing a brand new framework all on your own. So that's Ah terrible West off time. Instead, it would be a wise choice to use a well matured framework like cabinet that is specifically tuned to solve your problems. All right, I think this is a good start. Stay tuned 6. 02Things You Need: in this video, we're going to take a look at some of the things that you would need before we start working with Have been it, the first of which is Jessica or Java Development Kit. If you're able to write Java programs and run them comfortably, then that means you, although they have this installed in your computer. What you need to make sure, though, is that you have the latest one installed, and I believe since your enthusiastic about learning have been it, I assume that you know how to install J decay or upgrade to latest wash in. Then, once you have the set, make sure that you have a database management system software installed in your computer. I'm going to be using posed re SQL software. It is one of the most popular databases used along with job applications, and if you want to fall along with me, you can install the same database, or if you're comfortable with any other data base, you can use them as well. In this course, we're not really focused on database specific concept. Rather, we would interact with hibernate and having it is actually going to take care of interacting with the database. And that's the beauty of Harbin. It we developers don't have to interact with the database, but we would rather interact with hibernate and have been it will do the job for us. So for this course, it doesn't matter what database you use, but you need to make sure that you have some evidence off how database works. Some of the basic SQL queries, you know, joins etcetera. That would be a great value add, and also you need to be aware off. Some of the basic queries, like creating a database, are using the connection parameters to connect to the database etcetera, because these are the stuff that we're going to differ from Dera Bester database. So we just need to know those basics like connection battle meters, being able to create a database, using a command land or some kind of an administrator tool that is specific to your database, etcetera. And that puts suffice. And the next thing that I want to make sure is that you have an I D set up integrated development enrollment, something like a clips on that beans. Now, if you've been working with real World Java projects, then you probably know how to use Eclipse. And if you're not very familiar with the clips and you know how to use net beans or any other I D, then I would recommend you to switch to reckless because it is the most popular idea out there. And it has a lot of features that no other idea can support. If not, no, at least at little point of time, you'll be forced to switch to eclipse I d. Because it's a wonderful tool. And let me tell you, no matter what idea that to use, they also the same purpose off easing your development process. So even if you're using an idea like Net beans, it should be a very easy switch for you to download and install Eclipse and start using it . And this is the tool that I'm going to use throughout this course. So if you want to fall along, install eclipse. It's pretty easy. And once you install it just to make sure everything is working, okay, just create a sample Java project with the sample hello world application and then try to run it, make sure it is working, and finally you would need the habit framework and the list off other related libraries. It's a lot of pain, too manually. Don't let all these libraries and and set up the enrollment. So what I'm going to do is I'm going to use a project management tool like Maven. Maven is the most project management tool out there to help you manage the dependencies, etcetera. This will make our job a lot easier. If you're not ever off maven, you can still fall along and even work with the examples that I'm going to walk it through . Or, alternatively, I have a great course on the same. Just drop me a message and I'll see if I can give you access to that course. And similarly, I have a course on post three sq as well. It's a wonderful course, and that course, not only talks about was great skill specifically, but also it talks about PG admin, SQL in general and Jerry BC, along with the mini project, which is basically a crowd application. If you need access to that course, drop me a message. Let me see what we can do. All right. Once you have everything in place, I'm going to demonstrate the last step, though. But just make sure that you have all these three set up and installed and make sure they are working. All right, See you soon. 7. 02First Hibernate App Part 1: hold it. Let's get started with our first Cabinet example. And for this purpose, as I've already mentioned, we're going to be using living as a project management tool. And so I'm going to create the project using the same. If you don't know maven, then just try to imitate exactly what I'm doing. Click on file New and then Maven Project Click Next in my Melvin course. I've explained everything about all this prompts someone to click next. I'm currently isn't the default archetype, which is made an archetype quick start here. We can give any coordinates off or choice, but I would recommend you to give the same coordinates that I'm about to give. That's because actually have ready made files that I'm going to add into our project. And these files are actually tuned according to the naming conventions that I follow here. So in here, I'm going to say, calm dot company, an artifact that is going to be hetch be hyphen project or project despair. AJ, you can give any name off your choice. You have to take care off, making those changes in your palm that XML file. If you don't want to take that burden, Just you. Exact same name, click finish. So this is going to take a while. And while it does, I'm actually going to walk it through. List off steps involved to write off first have been eight application. You can open this file with the name first broke Step start dogs within which I mentioned all these steps that will help you write your first cabinet application. So the first step in it is off course here to have a database set up, which are the data visitor using you need to have at least one database created in my case . I'm using post area skill and its default database, which is post Greece. So let me just log into the bulls, graze shell, and I'm going to enter all the para meters like the server database port number. No matter which database you use, it must be having some kind off a command crossing tool like this. And you're supposed to log in and enter your database. So I'm going to enter the user name and passport for the database with the name pose grease , which is the default database in Bosnia. Skill. So have long been successfully now I can actually go ahead and create a table. However, I would like to leave that job toe happen it so I'm not going to manually create a table. The second step is to create so called a persistent class or sometimes termed as an entity class. This is the class whose instances would get stored in the database by Harbin. It remember this diagram that we had talked in one of four previous examples. So here we have a job object with certain values assigned to these fields and having it is actually going to take care off storing all these values in its corresponding table in the relational database, this particular object must have bean an instance off the so called a persistent class. So how do you term a class as a persistent class is when that class follows all these rules Now, these are not hardened fast rules. You can break these rules if you wish. If you think it makes sense to do so. But these are the standard rules off a Poggio are plain old java object, so it must not have any public fields. All the fields must be private and all the fields would have, public getters are centers, and that class would have one default constructor, and that particular class should not extend any other class. That has some fancy methods, and that's actually quite obvious. We want to keep things simple, just plain old Java objects, and the class must not extend our implement. Any specialized classes are interfaces that has fans and methods with some pansy logic and optionally. That particular class can be see realizable. It's highly recommended that you make it see realizable because more often in distributed applications, this frameworks would actually use the mechanism off civilization to convert the objects into byte stream, store them in memory and then returned back as objects. It has a very significant role, especially in distributed applications, and it's highly recommended that you implement see realizable interface for your class. So let's try to execute this particular step. I have got everything ready for you. Go to the list off downloaded files from this course, and you must be able to locate this particular fold of the name first hibernate example inside which you can look at all these files. You see this file with the name employed or Java. This is what our persistent class would be. So let's see for project is ready in our eclipse and Roman it is would expand this and inside our source directory under a sourcing main Java. We have one default class. We can get it off it if you wish. But what I'm going to do is I'm going to simply drag this last file into this particular package and make sure that we don't have any errors. As you can see, this is a Poggio it implemented realizable. We have one default constructor. Along with that, we also have a parametric constructor which we're going to use to assign values to all these fields will take a look at it in a while and then we have set off feels that we want to correspond them with the relational database table field and then we have the corresponding garrison seras. If you're trying to create this class on your own, don't try to write all these ghettos and set us on your own. It's always better that to generate the court automatically to make it ever free. So you go to source and he choose this option get us and centers. Currently, all the fields in here have their own garrison centers, so I got this prompt. Otherwise, you would get to select all the fields for what you want to generate ghettos and centers. So we got there. Let's move on with our next step. So the next step is to create so called a Cabinet configuration file, which would essentially help. They hibernate to talk with the database. So this is the file, very would provide all the connection para meters so that have a net will know to which database do you want hibernate to talk to? So if you go to the list of downloadable are downloaded files, you'll be able to locate this file with the name have been it dot c of Gerard XML. So let's drag this into the resources folder. So let's create that particular folder under Main. Let's create this folder with the name Resources inside, which we're going to put our convict file. Let's drag this down to here and let's see what's inside it. It's a very simple XML file. With all these tags having it. Conflagration is going to be the ultimate route tag inside which he would specify The session factory. We're going to talk about session factory, incoming videos, and then you have to provide all of these connection battle meters. If you've worked with database before, you probably know what this perimeters are. You would provide the driver details depending on the database that you're using. Since mine is supposedly a secure, I'm pointing to the post Gaskill driver, and here's a euro to my database. The connection you are. Oh, wherever your database is installed, this is going to be that I p address and then port in which your database is installed and in the database. And here we have the that database specific you Zinnemann passport, basically credentials. And then we have something new here, which is called SQL Dialect. Remember, have mentioned that have been. It takes care of translating the Hatch girl or have been it query language to a database Pacifica Skill statements. Well, that is possible because off this dialect, so depending on the database that you're using, you have toe provide this particular perimeter accordingly, Proposed agrees. This is what I have to provide, but for safe you're using Oracle, then that's going to change to this, and if it is for my ask your then it's going to be this. So just do a quick Google search and then you'll be able to get the have been a dialect specific to your database, and you just have to mention it over here. What we have next year is couple off tanks. This is not really mandatory, but it's always good to set this to true so that when we see the output on the council, we can see the list of SQL statements that were executed by hibernate. So show SQL Flag would tell, have a need whether do we want to see the instruction that it is executing in our database and former. The skill would instruct hibernate to show those resulting queries in human readable manner so that quickly that gets displayed will split up into multiple lines, and it would be easier for us to read. So what we have here next is But this property were sort of instructing have been it to update the database according to the changes that are being introduced in our entity. So when I said this to update, this is what is actually going to create a table in case of the table is not present in the database. If I don't have this property set, then we should be creating the table prayer to creating or entities and running our application. We're going to talk about this particular field incoming videos because you need to be aware off certain terms, like session and Session factory to completely understand various options you can provide in here. So we're going to skip it for now. But for the time being, this is needed. Just keep that in mind. Let's continue from next video just for your psychological satisfaction and then we'll understand what this mapping means. See you soon. 8. 02First Hibernate App Part 2: hold it. Let's continue with the next step as part of step for what we need to create is so called a mapping it similar file. This is XML file that tells hibernate which persistent class and its fields would map to which relation or table and its columns. Let me just walk it through the XML document and then you'll understand better. So you have this file employees dotage, b m dot xml To make sure that whatever the persistent class name that should you hear, it has to be same name in here as well. I'm going to drag this into our projects resources. All right, let me pull it again. So here we have as part of resources, let's see what's inside it. These tags are pretty straightforward to understand. Actually, we have this route tag having it mapping inside which you would space for multiple class files, essentially depot systems, last files. So you have the stag in here and he would specify the name of the trance along with its package. So this is our post system class, if you remember, and we're mentioning, but what table name is the table in the relational database And then we're just mentioning those two properties deciding in that persistent class in our case there just age and name . And here are age and name and the map to the relation database table columns with the name an age. So you provide this attribute column that maps to the relation that the best table. So essentially, we're trying to map this particular tribute off entity are persistent class, but this relation database table call them. And in here we're providing the data type basically water. The data time that you provide in here, same goes here as well. And then we have this field, which is I D. Which is also against pacified as bottle Depot system class. Whether forget about all of these annotations, we're going to talk about it pretty soon. And here is I D and is actually the primary key off the relation that the best table and these attributes are pretty straightforward. Your provide the name, which is I d Whatever is specified over here and then and then the type data type off the field and it's corresponding column in the table employees and additionally can also include this particular tag which is generator. This is like generating the identified automatically and in here again have multiple options. This school of these options are somewhat similar to what you would specify a spot off a database SQL query. If you know about generating sequences in s cure, then you can easily understand various other options we can provide in here in my database course, we talked about all of them. Creating sequences are to implementing the values, etcetera. So once we're on our application would be able to see what this is going to do. And specifically, we're going to check to see what is the skill statement that happen. It has executed to replicate the same. Now, once you specify this mapping file and tell have been eight, which persistent glass and it's fields should map to which table and its columns you'd have to mention that mapping inside your Cabinet convict XML file, just as we did here. And by the way, this particular file doesn't necessarily have to be an XML file. You can also specify this as a properties file, so it would name it as hibernate dot properties. But make sure that the name is hibernate and nothing else. And when you're specifying your properties file, it's going to look something like this. You'll get it off all these tags and institute. Just use these names like Cabinet connection. Euro equals the Ural similarly, would provide all the other para meters have dialect except a pretty straightforward Now we're pretty much done with our application. The only thing that we need to do is to write a class file that triggers everything. And that class file is with the name. Just don't Java. Let's pull it into our project and to grab this to the source directory. And in order to understand what's going on in here, we need to know something about sessions and Session factory, which will talk in next radio. But before that, let's try to fix these errors. Can you guess why these errors are coming? I'll give you two seconds. That's because we haven't done anything to use have been it libraries. And as I've already mentioned, Maven will make our job a lot easier. But despondent XML file went open. This and the company that goes inside the Palm the XML file is going to be this. So let's copy all the country from here, and this is the reason why I had mentioned you better said the same corners that I had said so that he won't get any crashes. So here we have those exact coordinates. I'm going to copy this from the Lexx, Mo. File and pissed it in here. So what am I doing primarily here is have included all the dependence is that are required for our Cabinet application to run. Do they can note that these libraries not only wearing truth, having it libraries, but also a few other related libraries, And it's very hard? Or I would say it's impossible or pretty time consuming to do all this on your own. It's very tedious job to search and Internet and download those jar files and then point to that class file's directory, etcetera. It's a big mess, so Megan comes in very handy, and it's a great tool. And in addition to that, by default, the default compiler plug in that comes along with maven would use Java 1.5 portion. So when it explicitly said this para meters to use the job awash in that you are using. So whichever the Dow abortion that you have installed. You can specify that version number in here, so make sure that you change this. And if you haven't provided the same corners that I had provided do make sure that you change them over here. Let me say this file and make sure that we don't have those errors anymore. So let me just quickly upgrade the project. I gotta maven update project, and this is certainly going to take a while. So let me this positivity and then get back. All right, Here we are now. There are no errors whatsoever. So we'll talk about what's happening in here, you know? Next video. See you soon. 9. 02Exploring The Main Logic: hold it. Let's try to understand what's going on here in this code. Nominee tells him that this is the business logic off your application, and he wanted to perform some kind of a transaction with the database using have been eight . So the first step is quite obvious in it to create Decision Factory, and this is how you would do so. You want to create an instance off the conflagration class, which is provided by the happen in itself. This configuration class will help you create Decision Factory using the configuration details that you set in this Cabinet XML file. So whatever you provide within this session factory DAG will be fed into the session factory to create the same. So you would make a call to this method build session factory and by default, it's going to assume that the configuration file is with the name have been eight Darcy of Did or XML. And that's the reason why I had mentioned that need to make sure that the name is same and moreover, this is this method is actually duplicated. I'm going to talk about it in the end of this video, but this will essentially create Decision Factory. The next step is to create this session. Isn't this session factory object? And the way you do it is by calling this method open session. And from that point, you can use this session object to perform your transaction. And here's how you do it. Pretty straightforward. You're too. Session dot Begin transaction. And in here he would perform all the transaction steps that you wish to perform. This could be a banking transaction. Like transferring funds are letting the user log in to his account. Except right could be anything but a single transaction in here. I'm going to keep things simple by Justin Stan Sheeting are persistent class, which is employees and that I'm sending some para meters to the Parametric constructor reciting in that persistent class. And I'm trying to say that object in the session. And this is equal into inserting this two entries into the table employees. We're going to see the end result and you'll understand what it means. And once you're done with whatever you have to do, you're going to say get transaction and come it. This is what will make the transaction complete. For example, if there is some kind of an exception that occurs within the transactional instructions that none of the operations will get saved have been. It will just simply rollback the database to its original state before the transaction. Well, this is similar to some of the transactional concepts we had covered in order the best course, but his how you do it like you begin the transaction, perform what we want and then you commit the transaction. If there is some exception, then no changes would take effect in the database. And once everything goes well, you need to take her off closing the session. As of all the Dimension session is not 1/3 safe object, so you want to keep it as short as possible. And here's how you do it now it's time to launch our application. But before that, let me show you the database, and I wanted to show you that the employee table is not already present, so it's not there now. If I run this program I'm expecting have been, it will create that table and also add this entry into the table. So let's on the program and see how it goes. It's expand this console and we're done. Let's go database and see if things are in good shape. And sure enough happen. It did create the table and also inserted the entry. In fact, you can see the instructions that have been it has executed. Now these instructions are specific to your database. So this may differ depending on the database and the dialect that you had used. So it has created the database. Isn't the fallen DTL and it has inserted an entry? Isn't the insert query as well? We're able to see all these messages because we had said these two properties. Now, if you're running this application for the first time, you may not be confident that it would work. And in fact, it's hard to say that it will work in the very first girl. I don't mean to say that I have flaws in my code, but I mean, there are certain things which are not in my control. For example, if you're using a different database, then you have to carefully provide all the required configuration details. If you mess up with it, then things may not work just in case. If things don't work, then then you would get some errors on the screen on the console. Quite understand what it is trying to fix the problem on your own. If you're still not successful, then the lot off on land resources one is a stack overflow and the other is off course. Google. If you do a quick Google search, you would most likely come across with somebody who might have faced the same issue that you're facing. If you're still not successful, I'm the last option. Now, let me tell you something. I can solve your problem. But it may not be a good idea if you want to learn because the best form off learning happens when you do mistakes and then you try to fix those errors on your own. So do keep that in mind. And I guess I also need to mention that we may not be following the best practices to write this code. For example, this method in here Bill session factory is actually the abrogated. I mean, if you go to the documentation off this configuration class, you would notice that this method is actually marked as dipper gated and is no longer recommended to use instead with your dues the same method with this perimeter service registry. Also, we're not really wrapped in this court around the try catch block. Well, I did mention that happen. It is actually going to take care off handling the exceptions. In fact, it is going to take care off handling the exceptions that are related two sq and other database later issues, but it won't handle the exception that occur in our code. So we went to take care off, wrapping the scored around the try, catch block and follow good practices. There isn't why didn't follow those good practices right now is to keep things simple, because if I have to follow those good practices, the number of lines off court with increase exponentially and our code may look little complex, although in reality it doesn't. So just to keep thing simple have written the following code just for the sake of explanation. But I'm going to make the necessary changes in this code, and I'll walk you through the court in next video. See, assume 10. 02Improving Our Code: hold it. Here is the improved Washington for code. Also the recommended way to write or code. So all the deal a significant increase in the number of lines of code. We're trying to follow some good practices here. So first off we have the static block within which were trying to call this method low decision factory. So in here we have the logic that does exactly the same. To load this session factory so that we can use the debt later point of time. And the significance off static block is something that I assume that you already know. This will get executed during the class loading time. But the key thing do not here is the way I'm creating the session factory. This time I didn't use that. Depreciated mattered, but I've done it in a different way. So I created the instance off configuration and that I'm trying to feed the conflagration xml file Do take note that I have no change. The name from hibernate to pose were skill. When you're trying to explicitly provide the name of the file like I did here, then you can give whatever the name off your choice. But If you don't want to specify the same, then you have to live it to have been a doxy of did or XML And what comes next is I'm trying to add resource the employee hatch b m dot xml. And this is basically whatever we give in here, same thing should go there as well. And since these two files are reciting in the Resources folder and not in the sub folder, I don't have to provide the complete part can just pacify directly the name of the file. Now here is the line that deserves some attention having it internally their so called so visas which are basically classes that implement certain standard interfaces. For example, we have connection provider, which is an interface that specify set off standard methods to maintain the data busy connections so that they have been it can actually acquired the connections and perform DB operations. And we have multiple implementations for that interface and each implementation different terms off how they manage the connections, etcetera. But all this implementation would ultimately solve the purpose off managing very busy connections because they all implement the same interface. So now then, what is this service registry in here. Well, service registry will actually manage. Those services that are used by the have been eight. And using this instruction, we're sort of building that service registry object and then feeling this object to the build session factory method to create our session factory. If this all sounds confusing, that's fine. These are all internal aspects off cabinet, and we don't presume have to bother too much about it. But, ah, you don't understand that you need to stop using the duplicated method, which is bill session factor, without any argument. But you should start using this approach, which is with the service industry, and the rest of the changes are pretty much Cordova concepts. You know what is static method, etcetera? And here's the same logic what we had seen in our earlier example. So I'm trying to get this session by calling this method get session and is essentially returning a session object and just off the code is pretty straightforward. And also, of course, I have put in a lot off try catch blocks in here to handle possible exceptions, and that's pretty much it. So for your convenience, I'm actually going to export this project and save it as part of the project files. So you should be able to download this and even import in Eclipse and Roman to take a look at what's happening in here. So living on this program and make sure there's working. But before that, I have actually deleted that table. So we get this error. Now let's run our program and save table gets created. And sure enough, it worked. All right, see you in my next video. 11. 02Incorporating Annotations: In my interview, you have mentioned that one of the advantages with have been it is that it supports standard GP annotations and by using annotations you can actually get it off this mapping file that tries to map depot system class with the relational database table, and we'll see how it's done. In fact, I already have the cord ready. I just have to uncommitted. So inside my persistent class, I'm going to UN command this tree lines. And if you notice we have another here, we have support for these annotations from couple of packages. One is from the Java expert assistance, and the other is from the hibernate. So which one should I use? Can you make a guess? Obviously, it's going to be job expert assistance. That's because let me do control shift oh, to import the class files. So that's because has evolved, we mentioned. These are standard JP annotations as well, so two more at later point of time. If you'd like to switch to a different or M tool that also supports GP annotations, then it's easier for you to switch. If you use have been, it's best if it can irritations the new Mafia certain challenges while trying for all tornadoes. So here we have annotations, and these are pretty much self explanatory. In this a mapping file. We have the class tag. So in here we have had great entity tag. Now, if you're used to enterprise Java beans, this is the entity bean, and by default, the table that's going to correspond to this entity. Bean is going to be with the name employees unless you explicitly specified with another annotation at the table. We won't explore. Rest off the annotations involved incoming videos, for sure, but I would like to keep this video very simple. So we also have a couple of fields along with the identify air. So we do have the idea field, and along with that, I've used this couple of annotations. One is to mention that this field is the identify air, which will be the primary key. And just as we specified a generator here we do have the generator here as well, and whatever the options that you can provide in here can go in here as well. Regiment similar, and you don't have toe explicitly mention annotations in here to tell hibernate that these are also the fields in the database having that can figure it out automatically and would create columns accordingly. So now guess what? By introducing all these annotations, I can literally get it off this file altogether. It's not mandatory that you need to delete this file. We can use both if needed. But I see no point in using XML document, and I'm not sure if I would ever use an example document for mapping. We're going to be using annotations and are examples, unless I feel there's a real need to talk about some of the tags involved in decimal document. So for now, I'm going to get rid off this. So let's dilated. And as a next step, if you remember in our convict file, we have this set and this pointing to the mapping XML fire. So I went to get it off this let me just come in this out and interact with this. So I had the same dag mapping. But this time, instead of saying a resource like an example, document or properties file, I said it's going to be a class file, and I would point to the persistent last and in it to provide the complete package. And I'm going to copy this and use the same, you know, test our job as well. But this time I'm not going to add a resource. Guess what I'm going to add. A class had annotated fast is what I'm going to use inside, which had mentioned that class file and then dark class as simple as that. Now, before I run the program, let me show you that I have deleted the table beforehand, so there's no table off employees. Now. Let me run this program and we'll see it. Get well, say, taking effect. And sure enough, these two queries were executed and same thing got reflected in database as well. So annotations are pretty in to do to program us to code because right when you're defining your fields, a programmer can also take care off how they're going to be present in database as well. So it's like more natural and into the way to write a program and also get it off all the all the mess with the maximal documents. So that's one of the advantages also, moreover, we have lot off tools that would help generate this entity classes from an existing database. So in case if you're not using having it before, but you already have a database, then it can still start with have been it. And you can use these tools to generate this entity classes from the database like you do the reverse engineering and ah, you can and you can get your we're going. We're going to actually see an example of the same as well in future videos. But one does that want age, though with sanitation is that if there's any change that you introduce in the mapping XML document, then you don't have to rebuild the entire application. But if you have any changes that needs to be incorporated as part off annotations, then you have to rebuild the application because we need the dark. Last file with those annotations reflected not really a big concern, and I think annotations is definitely a better alternator. But maybe if you're using earlier Russians off hibernate and you were already using these XML documents, it may be a little bit off in afford to switch to annotations. It may not be as smooth, but still it's possible, and there are tools out there to help you out with the same. So with this, I think we have a fair understanding off Harbin aid. I think this is a good start as well and we have a lot of exciting concepts. Incoming videos, so stadium. 12. 02Hibernate Auto Sync: we pretty much talked about all the components involved in our sample had been it application. But one thing I feel that we left behind is to talk about this property, which is part of the convict file here. We can actually provide multiple options so far, Reviews this option update meaning that we're asking Have Nick to check to see if there is any difference between the database schema and the scheme of that happen it is expecting, based on the per system class. Then we're asking have been made to make an update in the database to avoid any discrepancy is but we have multiple other options in here. We can also use create when he uses option create. This will essentially drop or destroy all the data in the database and is going to recreate everything from scratch when we initiate the application. So let me just demonstrate what this means. So in my database, I don't have anything at all, and I'm going to run this. So, as expected, it has created the table as well as it has inserted an entry. So now you should be able to see that limit on this program again. mid term net existing one, and then that's on it. So you see that happen. It has actually re executed all these instructions. That's because prior to these, it has actually dropped the table employees. So when you give the option as create, it's going to destroy everything, and then it will recreate everything from scratch, and update is similar to create. But it's not going to destroy anything. Only there is a need to upgrade the database schema happen. It will do that for us. The other option is validate, and it's pretty self explanatory. So this option will L. O. Have been made to check to see if there is any mismatch between the database and what it is expecting from the database. If there is a mismatch than happen, it is just going to try an exception. So let's make sure that we drop or database or rather, the table. So now employ Table is not accessible, so having it should ideally invalidate this and shows an exception. Let's on our program and see what's happening. And sure enough, it's a schema management exception and is pointing to this employee table and this saying it is missing and one last option that we can provide in here is to create drop. This is something interesting. This will create the schema when we initiate Decision Factory and when we closed the session factory is just going to destroy or drop off the tables in the database. So let's see an example of the same. And for this purpose, I'm actually going to close the session factory close. And so let's on our program before that. Let's terminate all existing process and run it, and here you notice that it has. It has dropped everything, and then and then it has created the table along with it. It has also added the entry as expected, but when session factories closed, it has also dropped the employee table just as expected. Although this is a very cool feature, we don't want to blindly rely on this in real world applications. We don't want to use this. Options like update, create, drop, etcetera. There's a little risk involved. So all this it's better that you use a safe option like validate, and then a database administrator will take her off manually, making sure that everything is intact. But for our examples It's absolutely fine. We can use any of these options and they work where it's moot. I hope it makes sense. See assume. 13. 0301GeneratorClasses: Okay, let's take a look at the various options we can provide as part of the agenda. The tank that goes under the I D tag, which will be the primary keen or database, so noticed or Java we have instance, created that persistent class, and we're trying to say that object in the database. But nowhere in here did we mention the identify for this field or for this object instead, we're asking Have been eight to generate. The are unfair for us, and the way we expressed it is with this tank, or we can do the same with an annotation. So now let's take a look at various options we can provide in here and for this purpose. I've actually created this document with the name generator dot dogs. You should be able to locate this in the list of files that you downloaded, the first of which is assigned when you said the class has assigned or when you have the same in the form of an annotation. Then we're telling hibernate that we will explicitly assigned the ardent fire on our own in our application in kids. If we don't do so, then depending on the database have been, it will aid the throw an exception, or it would generate an ad and fire on our behalf. So let's see how the behavior would be and gets off post area skill database. So in here I have this as assigned. And now let's try to run the program and prior to this have actually deleted the existent table. Now let me run this program. But before that, in order to better demonstrate, let me create a few more instances off this class, and then we'll try to save those objects. I'm going to call this use a 12 and three. Let's change the name to something else. He is DF. It doesn't matter. And maybe, um, you whatever it is, I'm going to copy this statement as well a couple of times. And now let's run the program and see how the output is going to look like so in kids off post area skill. How Bernie did not report any kind of an exception, although we did not provide any identify from our application, but instead it has involved a sequence with the name assigned and what is the sequence Now that is a concept off database, and we've talked about it. No database course, but if you don't know what is a sequence, then we have one example coming. So just hold on for a while to take a look at an example of the same. But depending on the database that you're using, the output may differ in your case, having admit through an exception, saying that you have to manually assign the identifier. So let's take a look at what's happening in the database, and sure enough, it has located some identify IRS based on the sequence. Let's go to the next one. What we have next is the generator increment. So when you use increment as an option, then we're asking happening to generate and identify where and every time it generates. We won't have been eight to increment the value by one, and the starting value would be from number one. But if you have some other process that is assigning and identify to that object, it will have the priority then having it will not incriminate the ardent fire. Instead, it will use the identity for that you're providing from your application. So let's take a look at an example of the same. So instead of assigned, I'm going to change this to increment led to the file and run the program again. So this time what I'm expecting is, since 10 is the maximum value from the point, Theoden Fair will get incremental. So let's do. And sure enough, we have 11 12 and 13. In case if there are no interest in the table, then the starting value would be one as simple as that. And here we have the sequence. So prior to experimenting with this example went to create a sequence in our database. In case supposedly, ask your I can create a sequence by using this instruction. And with this we're going to start off sequins with number one No. One. And from that point, we're going to increment the valley by one, which is the default value, unless explicitly specified over here. So when you try to execute this particular statement in database, let me copy the statement and go here. So it's 106 it showing 106 because prior to this, I've already executed the statement five times. So every time that you try to execute the statement. It'll increment the value by one. It's really hard to explain what exactly sequence in this video it is more often database concept, but I hope you got a sense of what it is. So let's move on with, uh, this example in here. So I'm going to use this sequence name in our tank just as we did here are with annotation . We're going to be introducing couple of annotations here. One is degenerated value here recon. Do any name off a choice, but the name has to be the exact same name. Whatever ugo in here. So basically, this is a name that we're going to use to identify a particular sequence in the database, and we also need to provide their location size, which in our case, is a default value, which is one that means every time we try to generate in ad and fire, this sequence will actually increment value by one. And here's the sample insert query. So instead of explicitly providing the ardent for value like 10 20 or whatever, I'm going this function next well and then Cirio the name of the CDO and this would generate according to the sequence So I'm going to copy these two lines off code, go back and best it in here. It's as simple as that. Now let's run our example and see what's going to happen. Okay? Seem to have some members. We have to import this class. So all the control shift. Oh, and make sure whatever you're importing are from Joe Expert assistance. There are certain class whiles the provide additional functionalities, but they belong toe having it package as a just not to use them. Because tomorrow, at that point of time, if you'd like to switch to a different or, um, tool, then it would be really hard to cope with the changes. So always try to use the classes in Job X persistence instead of having it specific classes , so that will be easier to switch. Now let's run artist program and see things are going to work and let's see what's happening in our table. And sure enough, it has generated the sequences. Now these are the most commonly used generator classes, but we have few other as well, although these are not very commonly used. I'm just letting you know anyway, so we have one with the value. Hell, Oh, this is going to generate the ardent fire by using so called a hilo algorithm. And the way it works is with this formula. When you're trying to express the same in your mapping XML, you have to provide all these three para meters. One is the table and the field. This will be the identify airfield and then he provide so called a max low and this is the best value on which this formula would be applied. So it's like, whatever the value that you provide 10 multiplied by one plus one and that will result in 11 based on the president's. So this will be calculated first on the result off, which would be added by one and similarly the value of one will get incriminated by two. We get 22 then again, 3 33 so on and so forth. I couldn't think off any real world use case where this would be useful. There might be some corner cases. I'm not sure, but we also have another algorithm which is this again. This is not very significant and we have gender to class identity. This is dependent on the database for my SQL and SQL Light. This is a cool into our to implementing the value and proposed Greece cure. It is serial. If you provide the type or the class as need. Ooh, Then that means habitable check of the database supports, which are the baby? Um, a softer you're using. Having it will check if it supports identity, which is this. If it's upwards, it will use that. Or if your database doesn't support identity, then it will check for sequence again if sequence works everything while I'm good. If it doesn't, then it will move on with the he login Raider or it will use the Hilo class. This healer class is not dependent on the database because this algorithm works on the cabinet end and the result will be assigned as an identify rare. So Hillary will work in any database that you use. And finally we have a couple off algorithms just like he will guard them. But of course, they work in different way, and these are primarily meant for string type. Identify IRS. So so for whatever we had discussed is for numerical type. Identify IRS. But if you have a string type. I didn't fire. And you want to use some kind off a generator and you can use this to algorithms. All right, I guess that's pretty much it. See you soon. Hold it. I think that's pretty much it. See you soon. See you soon. 14. 0302CustomGenerator: okay. We have seen various ways. Weaken gender the ad into fire by using various gender. Two classes in this medium went to demonstrate you how we can write our own custom, gender true class that we can use to generate the app identifiers for our tables. So let's say that I wanted to generate identify IRS in the following form like I want to prepare and each and every i d with E M. P. And then I put an underscore and then some random number something of that sort. So we'll have e m. P underscore some other random number. So let's see how it's done for that purpose. All you have to do is to create a class file and then unit implement this particular interface, which is identify rare generator and taken note that this is part off the package or have been eight. So if you're using this custom generator, your code may not be compatible with other Orem tools. So do keep that in mind. In fact, I think existing generators would suffice, but in rare cases Justin gets. If you'd like to generate your own, identify air, then you can go in this way. So once implement this interface, you're forced to provide the implementation for this method generate. And inside this method, you would have the logic, whatever the logic that you would like to give you to generate your desired identifier. In my case, I'm just trying to keep things simple. I used this object random Teoh gender to random integer, and I'm just trying to return by propelling hit with the string and inside my persistent class. This time I'm going to use this particular annotation that is part off the cabinet package , not the standard GP annotation, and I'm going to provide the falling para meters. The name can be anything off your choice, but the stategy is going to point to this class file, including the package, just as you see here. And then we can use this custom generator by providing the stag gender to value and then you provide the name. Whatever you give here that's older is to it. Now, if we run this program, you would come across with one ever Let's see what it is. Can you guess what that there would be just by taking a look at this code, I'll give you three seconds. Okay, let's take a look at the output and see the exception. So let's run the program. I'm sorry. I supposed to run the this job will file, So can you see anything in here? So here is the fixed. Set me to view. So what? We're passing from this custom generator it's a string. But what we have here is off pipe along. So let's change us too. String as well. So same thing should get deflected here as well as here. Now, let's try to run our program. And this time as well we're going to come across with another exception. Can you make a guess? Hold on, Let me on the program. So it stays the following, and I guess Okay, I'll give a clue in the database. We Although they have a table that was created with the data type as begin for I d Field. But we have not changed. It does string. So what does the fix that we can give? Having give you another clue, the fix would be inside this post area skill con Forget similar. Can you guess what the picks would be? The fix is here. I'm going to change this to create. So what this would essentially do is it will delete the entire table, and it would recreate we've already taken. Look at such example in our previous video. So let's run this program. And this time things will go smooth. Hopefully, Sure enough, it has dropped the table and it has created again. But this time with the data type as our car. And as expected, you would see the identify. IRS isn't the custom generator, so that's about it. So although I don't recommend you to use this package or cabinet to use annotations, I just want to let you know the flexibility that happen, it offers. Unless there is a real need with a solid reason to switch to have been eight annotations, try not to use them all right. Season. 15. 0401CRUDAppIntro: we have some solid understanding on some of the basics off hibernate. Now it's time to take a look at the very simple crowd application where we perform the basic database operations like create, read, update and delete in a typical real world Web application. This is how it works. You'll have some front, and technologies like HTML or GSP harnessed the end usable interact, and the records will get forwarded to a controller logic and something like so that will take the request and forward the request to the next layer, which will be services layer where the actual business logic will take place. So here you may use Enterprise Java beans, etcetera. But this business ladies actually going to instead initiate so called and data access object so data access object will have set off behaviors or methods, and each method will have a certain logic to interact with the database. In our simple crowd application, we're not really concerned about all these layers on top, but instead we're just simply going to replace the business logic with the main method, which will decide in a separate class. And this class will interact with the Dow class where will have all the list off methods that performed the crowd operations to talk to the database. Now I can walk you through how this is achieved, but I want you to give it a try before you move on with my next video. But let me just give you a glimpse off what we're trying to dio. Let's go to Eclipse. Okay, here is our doll class and here have introduced a few month. It's the first of which is to load Decision Factory, and then we have a mattered to create list off employees. I'm just simply going to use a for loop to populate the data, nor table isn't happening, of course. And then we have this read method which, when called, would written a list of all the employees residing in the table. And we have the update method, and we're going to pass the identify air, has a perimeter and based on the idea that we sent its respect to entry, will get updated in the database. Similarly, we have delivery card and we send an identifier as an argument and based on the identifier , we would delete an employee from the table and finally we got a deal. It all method which one called will deal it all the entries in the table and we have close session factory to close on Decision Factory. Pretty straightforward. And it's corresponding main method from where we trigger everything. And we call all those methods in our employees or Java, which is a persistent class. I have now made this I d part off this constructor. That's because in real world applications the idea will be sent automatically by the view layer. But since our application is not a full fledged NBC application, we have to explicitly provide the identifier from our main class. And that's why I had to have this in here. You'll see why when I the most with the example. Also I have over didn't diss mattered to string so that when you're trying to display objects off this class, you would see a meaningful string rather than some random set off characters and integers and in our convict file, have disabled these two properties because now we're performing quite a bit off transactions, and this is going to display all their skill statements. I don't want that to happen that will value the actual mess Agers. So I have disabled is for the time being, and I have said this property to update. Actually, I have intentionally left one issue with our program, and when I talk about it, I'll also talk about this particular field and in a pond or XML. I have actually added this library look for J, which is a framework now. This is nothing to get scared if you're not ever off lock for J. We're just using this just to disable some of the unnecessary messages that gets displayed on the console. We're still using the good old system dot r dot parental and everywhere we're not using the framework have used this just to add does that particular problem? Because when you get to see the output, we don't want to see all the have been it logs in here. We want to see whatever we're trying to display. So even if you don't have this, that's fine is just for our convenience. I've done that and we have this file lock for J, which corresponds to this framework not for Gerard Properties that decides under the Resources Directory, and I have said this to off. This is what will disable all the logging to get printed on the standard output. So that's about it. Try to write the program on your own. It doesn't necessarily have to be the perfect code, but just give it a try. I'm going to walk you through all these in my next video anyway, so see you soon. 16. 0402ExploringDAO: Okay, First of all, let us explore what's happening in this data access class. The first method is to load this session factory and the code inside it is pretty straightforward. And I'm sure that your ordinary ever off this have picked this court from our previous examples. And we're actually going to call this method from some of the other matters we have in the same class. Let's take a look at how we perform the create operation. So as usual, we have initiated a transaction using the session object, and we're committing the transaction. And between these two, we are performing the insert operation. Well, we know this instructional dirty, but the only thing changes in here is that I have added this full loop to add 10 entries as simple as that. And I'm trying to save each and every object while we looked through. And rest of the court is just as our previous example, nothing different. We have catch block to catch the exceptions, and in case if there is any exception and we're trying to roll back the transaction and we got the finally blocked to close the session and we have read method to read all the entries from the database. The court in here is almost similar to what we have seen in create method, but the difference is this spot. So here's something new we're trying to use have been it query language in this way to read all the interest from the database. So I decision don't create query and I'll pass in some string and this has to be having it . Query language we're going to talk about have been equity language in future videos, but for now, this is a statement that you need to use to read the data from the employee table. Also do taken note that you should not give the actual table name in here as we've already talked. This supposed to be the class name, the persistent last name. So this is going to return list off employees in the table and the beauty off this is we're not really typecasting are we're not taking care of converting this into our employees object. It's all done by having it automatically. And so we're able to directly Assane all those entries into the list off employees. So that's the beauty off. Have been it and in our update employ method. I'm passing in one argument, which will be the idea of the employees off whom I want to make some updates and all the code will remain same and only part that changes is this. So we're trying to get the employees using the statement session don't get and then have a passing these two arguments and I'm trying to typecast this to employ object. Well, I believe we don't have to do this. I can just get it off this And what comes next is we're trying to update that particular object by calling the forger matted, and I'm sending the new updated value. And finally we have the Delete Ricard method and we're passing the identify where the employees that we want to delete and, as usual, everything remains same except this part. So this time I'm trying to do session dot load and passing the same arguments what we had passed in here while updating and again here we don't have to really typecast our search, and I'm calling sessions or delete person that object to dilate. Well, you may be asking what is the difference between session not get and session, not load well in terms off functionality. It doesn't really matter much, but session that load offers lazy loading. We'll talk about lazy luring, inhabiting it. Incoming videos, for sure. But roughly speaking, Lord will not load the actual object. But it would rather load a sample object, which doesn't actually represent the existing object. And then when you're trying to do something, then the actual Lord will happen. That's when the actual object will get picked up. So only when we do something with it will the habit and get the actual entry or the object from the database. If the object is not present, then happen. It will throw an exception but coming to get. If the object is not present, then we just simply get a null value. So I really before we perform this, we should check to see if the object is now or not. Only then, with love Date otherwise obviously will get no point exception. So that's the basic difference. But we're going to talk about the lazy loading incoming videos for sure, and then we have this method delete all which will delete all the entries in the table. And here is again the have been it query language to do the same. And finally, we have a mattered that we're going to call the Close the Session factory or it, you know, next, Really, we're going to take a look at the main logic, and we'll also take a look at how our application runs. See you soon. 17. 0403TheMainClassAndRunningOurApp: Okay, let's take a look at what's happening in our main method. All the court in here is pretty, Is it? Understand? I'm not sure if I need to walk you through, but I'm just doing it anyway. So what we're essentially doing is to call all those methods in the Dow class one by one. So we're trying to add entries into the table, but calling this create method and then we're trying to read whatever has been added, and we're just sloping through all the entries to display them. And this is the reason why I had to override the to string method so that when you're trying to display these objects, they will be displayed in human, readable manner, and similarly, we're trying to update a record bypassing the identifier. In this case, I'm trying to update the employer with i d five and after I update, I'm again trying to display all the list off employees. And similarly, I'm trying to delete an employee with I d to. And then I'm trying to display everything. And finally, I'm deleting all the records in the table. Of course, we're closing the session factory in the end, so Let's take a look at how things will go that's run the program, creating the employee records. So after employees courts are created, we're trying to read the same. And here are the list off employees. And then we're trying to update the employee card with I D five particular, get the employees with I D five. His name is now updated with something else, and similarly, we're trying to delete the record with I D, too. So you don't find employees with. I did, too in here in this list dilated all the records closed on the session factory. But do take a note. Although we closed on the session factory, how process is still running? Can you guess why this is issue that I was talking. Let's stop this. Let's go to our doll class. So here is where we have the issue. Can you make a guess on what's going wrong? We have a serious issue, something to do with performance positivity and try to fix the problem. If you're not successful, just continue watching. But don't give up on trying, though, So here is where the fix needs to go every time you're calling this method from all these methods we're re initiating are recreating a session factory. That is a very expensive thing to do. You have to try to create only one session factory for application. And we want that session factor to stay alive as long as the application is running. So in here, we can just quickly check to see if session factory not equals no. Then we just simply return it return session Factory as simple has done so the session object is all that existing then would just simply return it. Otherwise, we'll go ahead and create one. No, that's tried to run the program and see if things will go well. Sure enough, After closing Decision Factory, our process is also done. I'm going to make this project available for you to download. So do give it a try. Other words. Just import the project and use mine. All right, see you soon. 18. 0502SaveAndPersist: in this video, we're going to talk about the following methods that are part off decision interface forces . Talk about these two methods in here. Save and persist. The job off these two methods is same is to transition the transient object to a persistent object. I mean, if you go back to the diagram, so we have our transient object and once we call session, not save and passes transient object as an argument. The job off that mattered at the save or persist is to transform this object into a persistent object. And once it does that, as of all the D mentioned, it will not represent the actual row in the table. So now, whatever the edit that you make in this object using its garrison centers have been, it will take care of updating the same in the database. But all those changes will not be saved immediately. They would be saved in some temporary location in a persistent context. And only after we perform ater transaction that comet or sessions are close. Will the hibernate save the details into the actual database? Let's see how it's done. So here we have pretty much the same court as previous. We're just using this method save to save this object, but it's not really saving the object. But it's just converting the strands and object to a persistent object. So now, after we do so, we can actually make some measures to this object. For example, I'm going to change the age set age 200 years. And now, after a perform, a ter, Come it. Our sessions are close. Have been It will persist all those details into a database. So let's on the program and see how things will go. So now if you go to the database, it would notice that we have an entry added with age 100. I'm going toe change this age to something else. Maybe 200. Let's be practical. That said it to 56 and on the program, and something would get reflected in here as well. So the point that I want to make here is the save is not really saving to the database, but rather it is converting the transient object into persistent object. And once it does happen, it will treat that object as the actual representation off the table row and whatever the changes that you make here is like you're actually performing those edits in the database and transaction dot com It will flush all the details in the temporary memory to the actual database will happen. It will actually take her off all that. So now, instead off save. You can also use the method persist, and it will do the same job that's on the program and see how things will go. And sure enough, everything worked well. So what is the different between saving? Persist. Well, save is not really part off the JPs specification, but we do have a method persist in JPs pacification. So just in case, if you're planning to motor different or I'm tool, then using processed would make little sense. You don't have to make too many changes in your code. Another difference is that when you call the same method, it is actually going to return the identify of that object or of that role, whereas positive returns wide. So let me diss quickly, demonstrate the same so we'll go here, make this to save. Get it off this For the time being, I'm going to put thesis out statement in here and I just tried to run the program. Let's put some kind off, some kind off a string in here, I de ese or whatever and run the program. And here it is. It has printed that into fire. So in some cases, it might be useful that you take their into fire. In that case, you can use save instead off persist. So essentially these two methods are same. They perform the same job, but the different terms off, how they're implemented and the type of founder that the return 19. 0503CloseAndEvict: Now let's talk about these two methods in here. San process helped us transform the transient object to a persistent object. And these two methods in here will actually help us detach the object from this session and get the object into a detached state. So if you go back when you call session dark clothes that will close the session and so there is no need off a persistent object or is there no purpose off a persistent object? So this object will automatically become voted into a detached object once a session gets closed. On the other hand, if you explicitly want to detach the object from the session, then you can use this method evict that will expressively take the object from the session . But the session would still stay alive. Let us try to take a look at an example of the same so that you'll understand better with all the Davidoff what session Dark clothes does. Let's start to explore the evict method. So I'm just going to get it off this to start statement from here, and I'm going to make some of days to this object in here, say, want to set the age 200 years. And after that, I'll do session dot have picked and I would provide that object in here and with the statement were telling have been eight that we want to detach this object from this session and make it a detached object. And right after that statement, I want to make one more update on that object someone to copy the same statement from here and make this to say, after six, my father run this program, What is the result that you're expecting? It would still be 45 and not even 100. That's because has evolved, mentioned when you're trying to make changes to a persistent object, then you have to either use session, not save our transaction Dark Comet to get those changes reflected into the database. But in here we executed this statement, but right after that, we've actually taken that object every from the session. So all of this changes will not take place at all. So it's on the program and see how things will go. And if you go to the database, you would know it is that we still have the value as 45. None of this state changes have taken effect, and this is exactly what I was telling. But this diagram, if an object, is either in transient state or in the tat state that no matter what changes were introduced to that object, things won't get reflected in the database. Now there is one interesting thing to note here. If you do, session not saved off the same object again. This is not going to result in moving this object from retired state to again persistent state that's not going to happen. Instead happen. It is going to create a brand new, persistent object and is going to persist the same. So until this point will have one entry added into the table. And after we detested object, it's no longer present in the persistent context and by doing session, not save again happen. It will create a new instance, which means we'll have a new row populated with a new identify air. So let's on the program and see how things will look. And if you go to database, sure enough, we have a couple of interest in here, and that explains it all right. Hope it makes sense. See you soon 20. 0504OtherMethod: Okay, let us explore some of the other methods that are part of decision interface. We've already talked about getting load and the difference between these two. But what they're actually doing is they're going to get the record from the database converted into an object, and that object would essentially be have persistent object so that we can do something with it coming to update and much to go to the diagram. We talked about how a transient object transitioned to a persistent object, and we've seen how opposes to the object is transitioned to a detached object without bearing merge. We're going to do it the other way. We're going to convert or perform transition off a detached object back to the persistent object, meaning that these two methods would help us add the detached object back into the session . So let's see how it's done. This is more or less our previous example here. We're trying to evict the object. So now the object is in that state, and based on our previous example, these two results will not reflected at all. Now let us try to perform update on the particular object that said, the file So before we did the comet, we're trying to get the detached object back to the session. So now if I run this program, I would expect the object Toby at its later state so the age would be set to 56. Let's on the program and see the results. And if you go to the database, sure enough, we have it set to 56. So essentially, in this case, have it did not take any effect at all because we reverted it with update. The murder matter will also do the exact same task. But there's one slight difference between the two when you're trying to feed the transition object to update its going to throw an exception. So here we have another object off employees, and this is transition object because it is not part off any session. So let me just copy this and feed this into update method and see what will happen. He would come across with the exception that says transition object exception. But then you do much things will work because much is actually going to create a brand new , persistent object, which is essentially copy off. Whatever the object that you feel in here and is going to make it part of the concession. So it's on the program and say how things will go. And if you go to the table, you would know this couple off Ricard's and those records would correspond to these two employees. If you use this method elite on a persistent object, it would make that object back toe a transient object self Apple assistant Object if you use delete would become back to a transient object, not thought of that session. And finally, we have this method save or update it a simply combination of both. Save an update, depending on which stayed the object ease the respect to task will take place. If the object is in transient state, then say would be performed to transform it into persistent state. Or if the object is indeed that state, then update will take place, which will bring the object back to this session and make it a persistent object. We're going to be using all these incoming videos, so see you soon 21. 0601OneToOne: in this chapter, we're going to talk about how we can maintain relations between tables isn't happen. Eight. Now I'm assuming that you know some of the database concepts like 1 to 1 relation one too many relation, many to wonder, elation and many to many relation. If you don't, that's fine as well. I'll try to give a real world example before I jump in tow. Happen it example. But in this video we're going to focus on 1 to 1 relation. And here is an example of the same little to have the employee table. And we also have the employees contact table where we'll try to store the employees. Contact details. Now, what kind of relation do we have in here? It's 1 to 1 because each employee can have only one contact detail, and each and every contact detail in here will have only one employee associated with it. For example, you can't have the same email i d from more than one employee. And why is worser You can't have an employee who is having multiple contact details? Well, you may argue that an individual can have multiple email ladies and multiple four numbers, but assume that I'm going to add another column in here, which takes the passport number off each and every individual or the employees. Then, in that case, every employee would have only one contact detail. And it's not possible that an individual can hold multiple passports if that's the case and you're doing something illegal. So what we have here is essentially Oneto one relation. One drawing here will have relation with one row in the employee contact table. As simple as that. Now, if you want to do the same with structured query language, then here are some of the instructions that you will execute in your database. You would create board this tables, and it would alter the employees contact able to add the foreign key. I mean, if you take a look at this table, we have one column in here, and this is the column, which is the foreign key, and that's what will help us relate this table with this table. So for each and every contact that we're going to add, we're also going to populate the employee I ity toe whom this contact belong to, so that we can maintain the relationship between these two tables. And that's how we basically maintained relations between tables is by using foreign key. And we had talked about all of that. You know, did the best course anyway. So going back. So once you create the constraint, the foreign key constraint by referencing to the employee table, he can just keep inserting values. You can either inserted row inside the employee table and by doing so, not really associating an employee with a contact detail. Maybe wanted top graders contact details at later point off time or whatever. But by just executing this piece off instruction, you're just adding the employee without the contact details. But when you're trying to add an entry into the contact table, it will not only provide the contact details like email idea and for number, but also it the point out the employees off whom is this contact belonged to? So you'd also populate the employee. I D. In here. Now let's see how we can accomplish the same with Harbor Nate, and for this purpose, I'm actually going to use the exact same code from our initial example. I mean, I'm just going to make some amendments to our first hibernate application to get this working. So the only thing that I'm going to add is Guess what a persistent class? And thats for another table that we have introduced the employees contact. So let's see how it's done. So everything is as usual, just as our first have been eight application. But the only difference is have added this persistent last contact for Java inside, which I have all the list off feels that I want in my employ contact table. Also do they can know that I've introduced this simple annotations at the table would let us give a name to our table, and this will be the name off the table in our database and similar levels introduced This annotations had read column to give the name off these columns. So although we have I d in here in the database, would have it stored. Are would have the column name has contact I D. So nothing fancy here, So everything is same just as employees class. And if you try to run the program now, this is going to create the employees contact table, but it will not have any kind of an association with the employee table. So how do we create an association? It's pretty simple. You just have to add couple of annotations and here we have it pretty easy. So this time we used our custom data type, which is the persistent class employees. Now no relation would be established by just specifying the statement. You have to introduce one key annotation. He is this 1 to 1. That's what will make the stable, have oneto one relation with the employee table or whatever you specify in here. So along with this annotation, we have said couple of para meters. One is the target entity, which will point to the employee class. You don't really have to specify that having it is smart enough to figure that out by taking a look at the data type in here. But it's always better to be specific, at least for dollar purse. It would look more clear, and we're going to talk about this casket type incoming videos for sure. So let's hold on for the time being, and that's all there is to it. Nothing complicated at all. Now, off course, since we've introduced a new persist in class, we also need to take care off Adam the same as part off our conflict file, just as I did in here. And also, you know, test or Java have added another annotated class like Sil. And here's our code, which will actually add the entry into the database. But before you run the program, make sure that you delete all the tables from the database. And so here we have created the employee object, and we've also created the contact object. But here we're passing the employee object in here. So in the database, whatever will be the idea off this employee the same I d will get stored as a foreign key in the contact table. And finally, we're trying to save the contact object. So once we do so, it will not only add the contact details but also would take care off, adding the employee details into the employee table since the boat or now related and rest of the court is just as of our first initial happen it application program and that's holy restored. Let's run the program and see how things will go. And by the way, I have already deleted the table. You can see that we're not able to see the employee table. And let's take a look at the output. All right, we're done. So okay, happen. It has actually tried to drop the table. If this is existing and sending goes in here as well drop table. If employees is existing, the reason why we have an exception in here is because prior to deleting the employees contact table, having it has actually tried to drop the constraint, the foreign que con strain. Since there is no table, it's not possible to drop the constraint. And so we have an exception. But the good thing about happen, it is that it has handled that exception and we don't have to take care off it and going forward, it has created about the tables and also altered the table the contact able to create the foreign key just as you see here and then finally have been, it has inserted the data into the tables, so let's see how things will look in the database. So we got our employees populated and also employees contact. So this idea corresponds to Mr Asunder in case a furious and XML document. It's nothing complicated. All you have to do is to add the following tag in your XML file and all these fields are pretty much self explanatory. This is the employee class, the child class. We're going to talk about the cascading the name of the I. D. So you would just create a file, something like this. Like we have employees. I don't have to be. I'm not XML. You would now have the contact dot h p m dot xml along with all the properties that deciding in the contact persistent class, you would add that one on one relation in here, but you can just simply use annotations. No need to mess around because when you add this while again, those changes should get reflected everywhere else. And here we have toe point to that file. As one last, you have to add a different mapping entry, something that goes like this. So if you take care off all that, you're good to go. All right. I guess that's all for this video. See you soon. 22. 0602Cascading: in this video, we're going to try to explore this option. Casket type will understand what is cast getting etcetera. But before that, I want to let you know that I have said this option to create so that every time you run this test program, having it is actually going to get it off existing schema and is going to recreate everything from scratch have also incorporated certain amendments to this code so that it looks little clean. So we now have these two method calls when its students are the employees with contact and the other is to delete the employees with contact. The start explored. This mattered in here to insert the employ with contact. So the court that we have here it's pretty much the same core that we're seeing in our previous example. But I want to let you know that if you want to accomplish the same task using SQL statements, then this is how you would do it. You would create about the tables and then you will add the foreign key constraint for the employees contact table, and then you will first insert the employees and then you will try to insert the corresponding contact details. It's not possible that you run the squarely first before you try to add the employees. When you try to do that, you would see an error saying that you need to have a foreign key that maps to an existing table row in the employ table. But if you take a look at the court in here when you're trying to accomplish the same with hibernate, we're not really trying to perform to insert operations were trying to say only the contact object and having it is actually going to take care off, inserting the employee object as well. How is this happening? That's because off the option that we had set in here. So when you say Cascade type and you said it to all for all the session related operations happen, it is actually going to take care off cascading because heaven, it is aware that these two entities are related to each other and the border having oneto one relation. So let me just demonstrate you what I mean. For example, if I try to get rid off this option, then happen, it is not actually going to perform any cascading and so it's going to throw an exception, lets on the program and see how the output looks. Let's stop the existing program. So if you notice we have an exception in here and that has happened when having it is trying to insert the employees contact, that's because we haven't saved the employees before. We try to perform the insert off the contact details and let's take a look at the message that gets shown up in here the object references and unsaved transient in stands. Which means it is saying that there is no employees existing, so we cannot add the contact details off him. And it is suggesting us to save the transient in stands before Flushing. And it has also pointed the instance that went to Persist employees. So I really we thought that cascading Options said what we need to Dio is to perform another similar transaction till in the first transaction, were actually going to save the employees and then we'll try to save the contact details. So now we have this couple off calls to the same method when it's to save the employees that there is to say the contact just as we're doing here just as we have a couple off inserts. We have these two statements in here. No, let's start on the program and everything works well, and you would see an entry in the database as well. It's there as well as and employees contact table pretty well and good. So in order to award the trouble off you having to write so many transactions, let me just quickly undo all the changes. You can just simply set this option two casket type, all so that happen. It will take care off, adding the employee first before it tries to add the parent object contact. So that's what is gas getting inhabit Nate. Now in here, we have multiple options to choose from. For example, if you want cascading toe happen only when you try to remove and enter from the table, then we can say remove from here now. So with this cascading is not going to happen when you're trying to perform the insertion. So again this is going to throw an exception. Let's take a look at how it looks, and, as expected, it is pretty much saying the same to add the employees before you tried to save his contact and let me just quickly repeat the same thing that we've done to perform couple off save transactions. So this is going to work. And then let me just un commend this method to delete the employer with the contact. Can you make a guess on how the court would look like to delete an employee with contact? The task is pretty much similar to what you would do manually using SQL statement so we would try to fetch the contact closed on its identify ire. I'm trying to keep things simple here, so I'm just explicitly providing that into fire. But as of all the dimension in real world applications, you'd get the identify are automatically bills. Don't what use the chooses, and I want to get this contact object you can just simply do. Sessions are delayed, and you would pass this object now, since we said this option casket type to remove, having it is going to perform the cascading for us for remove operation. So when you do delete, it's not only going to delete the contact details, but also its associate ID employee details. It's a limit on this program, so this would insert all the details and then is going to delete as well. But we got in there. Let's take a look at what it is. Okay, this is saying that there's no default constructor for entity employees. Well, that's the reason I mentioned that he had to follow those Poggio good practices. Um, open up this particular file, employees. And and sure enough, we don't have the default constructor in here. So this is a learning for us. We have to follow those Poggio good practices as much as possible because this different constructor is going to help happening to create instance off employees. And if you don't want to see all these side effects again, just follow all deported good practices. So I've created this. I believe we don't have the default constructor here as well, but we do. That's great. So now things should go smoothly. What's on the program again? And sure enough, it has added the entry and then it has also deleted the employees. And here's the statement and happened. It taken care off joining and all too, to perform joint operations off both the tables to relate the entry and you don't have to deal it with multiple transactions as search. But now, if I get it off the statement in here now, can you make a guess? On whether do we see an exceptional not hold it? Let's see. The answer is, we don't see an exception. Let's on the program and everything works well. Can you guess why? Well, it's not possible that you have the contact details often employee, when the employee is not present. But it's possible the other way. You can have an employee without having his contact details. I mean, since we have the foreign key constant on the employee contact table, you cannot get rid off the employees associated with the contact unless you get it off its corresponding contact details. But it's possible the other way. What we're trying to do here is to delete the contact details, and that's all. We're not trying to delete the employees as such, and have a neat is not going to take her off dilating the employees because we removed that option. Ask Ed. So now if you go to the database, you won't see employ contact. But guess what you would see the employees and uh, that explains so similarly can also perform, update and read operations, and they both are pretty straightforward. And it would pretty much do the same thing. What we've done in our crowd application, I'm just trying to explain this option in here cascading. So it again is it when required? So we have all the options that that are part off a session object. Detach, merge. Persist, refreshing, removed. I'd like to keep this toe all for the time being and let me bring back all the changes. And then I'm going to make this project available for you to download, and you can import it into your eclipse and Roman to work on the same. So try to take the score and try to experiment with the various options we have and just simply play around with it. All right, See you soon. 23. 0603OnetoMany: in this video, we're going to take a look at how we can manage one too many relation using hibernate if you take a look at this example Diagram. We have Boss Table and the employee table, and these two tables are having one too many relation. I mean, single boss can have multiple employees, but it's not the other way. A single employer will not have more than one boss, at least for the sake of this example, Let us assume so. So in this example, if you notice we're trying to map these two tables or create relation between these two tables isn't the foreign key. So in here we have a couple of employees, Rahul and Bob, and they both are pointing to the boss i D, which is 1002 which corresponds to Sunder. So understand. There we have Rahul and Bob, but none of these employees will correspond to multiple bosses. Very obvious. So in this diagram we have Bastable as the parent table and the employee has the child table as it has formed. Can it? And so in Arhab, innit? Example. We're going to have a couple off persistent classes when it's for boss and the other is for employees. And still, this is one to many relationship. We want tohave, the mapping done from the boss persistent class. So we're going to specify, are one too many annotation inside the boss poor system class. And then, later on, we would be able to instance she ate the boss class. And then we're going to feed an object off employees. But how it's done, Let's take a look at it. So here we have the boss, persistent Glass and the employees. And as of all the dimension since this is one too many relation, we're going to have to have that mapping done from the parent class to the child class. But the key thing to note here, since it's one to many relationship, you know, toe hold that many objects you can't specify a data type that holds a single value. You need to use a collection something like set or list etcetera in this case arm using set , and have also mentioned that the set can have elements off type employees and along with that, we also have this annotations, which is one too many, and this is a key annotation that will do the magic and target. And it is going to point to the employee class and gas getting will come into picture when you run the program and join Table is going to join a new column to the employee table, which will be the foreign key. And the name of that column is going to be this boss eyed. Whatever you specify in here and this maps do. B. I. D. Column off Boss Table and Employed Class is pretty straightforward. You don't have any fancy annotations there. And in Artois Java program Celestic will get the insert logic. And as you would expect, we're going to create couple off employees and then we're going to add them into a set off employs. And finally, we're going to create the boss. They're supposed to be boss, just a good naming convention there. So inside the boss object to the constructor. I'm going to pass the name of the balls, his age and the list off employees who work under him, and I'm going to save this object. Rest is all as usual, so that's on the program and see how this works and pray or to this. I've actually cleaned up all the tables from the database of manually deleted all the tables just to keep things clean before we run this program. So it's on the program and see how it works. And sure enough, it worked pretty well just as expected. And if you go to the gun soul slash DT after display all the tables that are present. So let's see what's inside the boss table. Select Star from Boss Select Star from Boss Pretty good and then select star from employ and the result is as expected. So we have the foreign key and it points to this entered in here in the bath stable. I must take a look at the other operations that were performing me to stop this program. Media's quickly uncommitted this So in here I'm just trying to get the details, and the logic is pretty straightforward. So it's in here, get details. Or rather, we want to display the boss details and for this purpose have actually created are over it in the two string method to display that object in some meaningful fashion. And I'm just trying to fetch the boss object from here and then I'm trying to displayed as simple as that. Let me just also uncommitted this piece off gored to delete the boss entry. And since we have said the cascading type two all this will not only delete the employees with i d or Boss with i d one, but also its corresponding employees first run the program and see how things will work. So as you notice, but able to display the boss details in here and, uh so here, actually the list of employees is displayed in draw from. So if you have the two string method overridden in employ class as well, let me just quickly do that. So I go to the end and I'm going to make use off Eclipse feature to gender. The court for us has some blood that looks of the file and on the program again. Let me close this. Let me stop that. And sure enough, you have everything displayed in user friendly fashion and then later we're trying to delete the interests. And if you notice you don't have anyone inside the stables and obviously I don't have to mention that if you based on the cascading time that you set in here, things will change. Forget it off this, then cascading will not happen. Then you have to manually perform a couple off tasks to delete the entry from the employee table. And then you would delete the entry from the boss table. Okay, that's pretty much it. But the only thing that I feel is missing is the update operation. Can you try to figure out how it can be done? It's pretty straightforward. So let me just quickly replace this code for delete and do. An update I'm going to do is to set his age 200 years. Well, just for the sake of this example and instruct delete, I'm going to say update, and that's all there is to it. And after this, it's also display displayed the the boss. And then you'll see what sub dated. Really? It's on the program and sure enough, Okay, here the ages still shown as 45. But if you go to a database and see what's happening there, the age is updated. Now, Can you guess what's going wrong in here without code? Have you figured that out? Hold it. Let me let me tell you. It's very easy to fix. There isn't why. Still, the age was shown as 45 is because when you're trying to display this particular data off, employees would still have the values qualified because we haven't yet committed the transaction. So let me just try to display the details right after we commit the transaction and let's on the program again. And this time he would see age as 100. Isn't that beautiful? All right, that's it on this video, see assume. 24. 0604ManyToOne: in this video, we're going to take a look at how we can deal with many to one. Mapping isn't have been eight now. This is not a very popular data business and approach. Most database designers would rather prefer to use one too many mapping over many to one mapping. But just in case, if you're curious on how happen it deals with it, this really explains the same. So as you can see, the diagram is going to remain pretty much the same as with one too many mapping. But in case of one too many mapping we have defined are mapping or our relation with the employee table inside the boss class with the annotation one too many. But this time we're going to define our relation with the boss table inside the employee class. And as your guests were going to use the annotation, many to one so many employees can correspond to a single boss, so let's see how it's done in the code. So here we have the boss class and it does not have any fancy annotations. We used to have one too many mapping in here, but now we got rid off it from here and for many toe one mapping. We have to define our mapping inside the child class, which in this case is employees. And here we have it. So here we have the sanitation, many to one, and its target entity is going to be the boss. Class happens, were explaining have been made that descended the employees going to have many to one relation with the entity boss. Well, you don't really have to define this, even if you don't, that's fine as well, because having it is smart enough to expect that based on the data type in here and then we know what cascading is. We have this joint column and it does the same job as with our previous examples. Nothing really different. But this time we're going to create in stands off employees. Well, we're going to create an instance off boss first and then we're going to feed that object to employ object and for the very reason we have this constructor about a meter that takes in the instance off boss class and rest of the code is pretty easy to understand. We got get us interests and until string method onboard these classes just so that we can display details in some meaningful way. So here is our insert logic. And as you would expect, you'd create multiple employees. And before that you have to create an instance off the boss class with required values. And then you're going to send this object to the employer, object to its constructor, and finally we went to begin the transaction and save these two employees into the database . So that's how it's done. Very straightforward. And since we had said the cascading Type two all having it will not only save the employer object, but it's also going to save the boss object before persisting the employee object. And let's take a look at how we can extract data from the database. And here's how we would do it. And it's pretty straightforward. So we're trying to display the employees by fetching it, using the identify air. So let's see how things will go. We're going to talk about delete in a while. It's on the program, incredible and good. Let's see what's happening in the database. So I've already deleted all the existing tables before I ran this program and if I don't slash. Detain, pause, grease. We have list off tables, so select star from boss stable. So we have, our boss added. And so let's start from employee table. And sure enough, these two employees would correspond to boss with Heidi one s and Blouse that now coming to delete operation. It's little tricky because it's not possible that we can get the employees details and then we can delete when we have the cascading typeset to all. That's because it's not possible that we delete an employee and expect Cabinet to also delete its corresponding bars because that boss object may have some relation with other employees in the table. Well, when I say relationship, it's database relational, a real world relation. So for that very reason happen, it is not going to perform the delete operation. At the same time, you can't fetch the boss object and try to delete it, because there might be some employees who have foreign key relationship with that boss. So what is the solution? Well, there are multiple ways you can deal with this. One simple approach is to get it off the cascading type, which is in here. Just get it off this, and then you take it off manually, deleting each and every entity. So you would do it all the child objects first, which will be list off employees that are dependent on a particular bars. And then you have complete freedom in the world to delete the boss object so you can go with that approach. Or alternatively, you can also use one too many approach. Just as we've seen in our previous video are alternately can also go with bi directional mapping, which will take a look at incoming video. So if I try to delete, we're going to see an exception. So I've just committed this out for the time being. Oh, let me just get rid off this because I'm going to save this project for you to download. And I don't want you to mess around with this method, so let me just get it off this. I'm going to say this project for you to download. All right. See you in my next video. 25. 0605bidirectionalMapping: in this video, we're going to take a look at bi directional mapping in simple terms. Bi directional mapping. Is this combination off one too many and many to one. When I say combination off this, too, I'm also going to combine both the examples that were taken Look at So I picked the boss class from our one too many example, and I picked the employee class from our many to one example. So we have many to one annotation in here and one too many annotation in here. So now let's take a look at what's going on in here. You can either create the boss object and set list off employees. Hourigan Dude the other way. You can create the employer object and said the boss object that corresponds to that employee so you can follow either approaches to populate the database, but in this approach, have created a couple of employees and offset boss for each one off them. Pretty straightforward. But let's take a look at the deal. It matter. That's where we want to address the problem in this case, have used one to any approach to delete the boss object, and since I had said the casket in type two. All this is also going to delete its child objects, which will be a list of employees that are dependent on this boss object. Pretty simple. But if I run this program, we're going to see one strange exception. I'm here on the program and see how things will work. And before I do, I did delete the existing tables from the database just to keep things clean. So we have pretty big exception. Let's see what it is. You go back, stack overflow error. Now, where do we have the problem? Can you make a guess? Well, let me give you a clue. The problem is, with the two string method in here and the testing method in here, how can let me give you another clue? That exception occurs when you try to display the details. So when we call this method, we get that exception. And it has something to do with this to string methods in both the classes. Okay, let me explain you what's going on. So here we're trying to display the boss details and inside the testing method off the boss class we're trying to display the employee object. And again, this is going to call the toasting matter off this and again become across with this boss object again. Java will try to display the employ object, and it goes on and on forever. How can you stop that? In my case, I just got it off displaying this object from here. And things will go well. And if you go to the database, you don't see anything at all because we've also deleted off the stuff. All right, that's about it. See you soon. 26. 0606ManyToMany: in this video, we're going to take a look at how we can manage. Many too many mapping using have been eight. So now what is many to many mapping? You can understand the same based on this diagram in here, so we can have multiple employees and rolling for a single course, and we can have multiple courses and rolled by a single employee. So that's many too many mapping. And the way we maintain this relationship is with another table that just combines the form case off both these tables. So in here, you can say that employees with I D 2001 has enrolled for these two courses with I D. 1001 and 1002 which corresponds to Java and have been eight. And similarly, we have a couple of employees with desire identifiers t 03 and two or two and the boat and rolled for the same course 1004 which corresponds to pose great skill course so in or having it example. We can deal with this in couple off. Phase one is to introduce the many to many annotation in either off this persistent classes , so either off these classes would own the relationship are we can make it bi directional and specify our many too many annotation in both these classes so that we can create either of these objects to add an entry. So we can either create an employee object and fearing list of courses are we can create a course object and give that object list off employees who want to enroll for that course. So let's go to clips and take a look at how it's done. So here we have the employees class as well as the course class now inside the employee class, I have defined the collection off type course so that we can set list off courses while trying to add the employees. And on the other hand, in the course class, we can add list off employees, so that's many too many mapping. But you also need toe, of course, mentioned the annotation on board the ends. The target entity points to the target entity in case of employees. This points to the course class and wise versa in case off course class at this points to employ class, and you don't really have to define this because against having it can figure that out. Is dawn the type in here? And we know this option casket in type that will come into picture when we on this program . Now, here is something noticeable here. If you mention joint table, we can actually create the store table in here. This is what maintained the relationship. And along with that, we've also specified couple of columns in here that corresponds to the primary keys off. Both the tables are in the stable. There would be foreign keys, so you would specify a couple off joint column annotation as part off joined table annotation. Just as you see in here, you have to follow the following syntax with Kali braces and all. And you would provide the name of the column off the current table, which corresponds to employee I. D. And you also mentioned the in most joint columns. That means this would be the column of the target entity, which would be course I d and ah, So let's take a look at the description off in Most joined Coleman, and you'd understand better. So this is an optional parameter that we can set that spot off the sanitation. And that is basically the former Greek columns off the joint table, which reference the primary key off the entity that does not own the association. That means in this case, this association is owned by the employee class. When you're defining a column that refer to the primary key off another table, then you have to mention it, as in Was joined. Column out of it belongs to the same class, are the same table. Then you can just mention it with the joint columns as simple as that. And you pretty much have the same annotation defined inside the course class as well. But this time the employee idea is going to be in Western columns, and the joint column would correspond to the core society. Well, I guess you don't really have to mention these annotations in here. If you don't specify these annotations than have a net will actually do the job for you. But if you define, you'd have the flexibility to define the column, so that's pretty much it. And if you go to the main class, our main logic, I have a couple off methods at it, one is to perform the insert operation by creating an employee object and the other is to performance. That operation is in the course object, and just by taking a look at this code, it can easily understand what's happening in here. I really don't have to walk it through this pretty easy to understand. And same thing goes for religion update. I would like your experiment with other operations like Delete Update, etcetera. Give it a try. It's pretty easy to accomplish, and it's pretty much similar to what we're seeing in our previous examples. So that's about it. We'll see you soon. 27. 0607OrphanedRemoval: in this video, we're going to talk about our fund removal. So what we have here is the same example that we have taken a look at when we talked about one too many relation. And one boss will have multiple employees that work under him. And it's not possible that there can be an employee who does not have any boss. So in this example, when I run this program, what we have here is list of employees and each would have had boss associate ID. But there's a little flowing our code. Let me demonstrate what I mean. So what I'm trying to do here is have actually fetched all the list of employees in here, and then I'm trying to remove an employee from the list are from the set, and the employed that I'm removing is the employee with identify are one. And then later on, I'm committing the transaction. So according to you, what is going to be end result? Are we going to see this employee getting deleted from the database? The answer is no. When you have set the cascading type two all which also includes delete operation, then only when you perform the delete operation with the cascading happen. So here we're not really performing to delete operation in the database. We're just trying to remove the relationship between a boss and an employee. Now let's try to run this program and see how things will go. And if you go to the database, he would notice that we have an employee who does not have any boss at all. This is unacceptable in our scenario. Each and every employee should have a boss so clearly way to fix this somehow. And the solution to this problem is you said this para Meter, he said. This option orphaned removal. True. So what this means is, when you're trying to delete an object from the list off employees or list off employ objects, then that removed object is actually in an orphan state. When you have this option set to true, it will not only remove the relation between the boss object and the employer object, but also is going to remove that corresponding employees from the database. So no illustrator on the program and see how things will go. And if you go to the database, sure enough, we have that employees getting deleted, so that's about the orphaned removal option. Hope it makes sense. See you soon 28. 0701FetchStrategies: in this video, we're going to talk about various fetching strategies used by have been eight toe fresh to details from the database when we try to perform the load operation. So what we have here is the boss class, and we have defined the mapping with the employees class in here so each boss will have one to manipulation with the list off. Employees now assume that we have 10,000 employees under a single boss. And when you're trying to display that particular boss object, should they have been a display the boss object alone? Our Should it also display the list off employees that are associated with that boss? Will. This fetching stategy defines the same there. A couple of strategies. When is the fetch type lazy and the other is eager loading. This was talk about lazy loading. So when you have the Fed strategy set too lazy, having it would just fetch the employee object but not its associate ID. The stop employees. So when does the have been it? Fetch the list off employees is when there's a real need to fetch employees. Let's take a look at an example, and you would understand better. So the example that we have in here he is similar to the one we had taken a look at when we talked about one too many relation. The only difference is a guarded out that delete method from here. So inside the inside method, a matting list off employees to the boss object, and then I'm trying to store the boss object into the database. Since we have the cascading option set toe all this will also save the list off employees along with the boss object. So now let's take a look at what's happening in this. Get details mattered. So what we're trying to do here is we're trying to fetch the boss details past object to be specific. And then after that, let me discreetly copy the statement to display that boss object. So now what is your gas is going to be the result off these three instructions in here. So I'm just trying to display the boss object in here and also note that I have now disable this to string method. I'll explain why I had to do that. But here I'm trying to display the boss object. And after that, I'm trying to get the list of employees in here. If around this program, since we have the fetch typeset too lazy have been it is just going to perform one select query to get the boss object. But it's not going to get the list off employees. Let's on the program and see what's happening. So as you can see, it has fish the boss details like Boss I D. Boss age and boss name. But nobody in here do you see employee objects, and that explains everything. So although we're trying to fetch the employee details in here, there is no real purpose off it. After officially stuff, employees were not doing anything with it. So let's do something with it so that we were telling have been made that Yes, we do have a real need for employees because we want to display it on the console. So I am just looking through all the list off employees and trying to display it. And now Cabinet would actually fetch the list off employees that are associated with the glass object. It's on the program again, and this time you would notice that have been It has not only fetched the boss object, but also fetched the list off employees. And here are those two. So these are getting the spread from the toasting matter off the employer object. So the reason why I didn't enabled this testing method as part of the that is part of this boss class is because if I enable this then having it things that there is a need to fetch the employee details because this will get displayed on the console enter is just going to catch everything, regardless, offer for doing something in here or not. Let's on the program and the result would be has expected. We got a couple off, said a statement on its to display the boss. Another is for employees, so that's about the lazy lowering. So what is the real purpose off lazy loading? Well, Liz Alluring has a significant role in improving the overall performance off your application. And ultimately, the user experience as well, for example, lets it that you've logged into your Facebook account and think about a situation where Facebook keeps on loading all the posts that ever existed. That would happen if Facebook was quoted in such way that the lazy loading is disabled. Since the logic behind the Facebook is Leslie lowering all the pose, you're able to see the pose only on demand. So as you scroll down the page, the post will get displayed. And that happens. You too. Lazy loading and Lizzie loading can also be absorbed in all the commerce websites. You don't get to see all the list off products that ever existed. You would see a few of them, and as you scroll down, the product would keep popping up. So that's about lazy loading. And the other option that you can set in here is eager loading. And that's simply the opposite. Awfully easy loading. So in case awful easy loading, it has performed a couple off select queries to display but the object. But now, if we run this program, you would know it. ISS that happened. It has actually performed the joint operation to be able to get the boss details, so it has not only fetched the boss details but also list off employees. So that's it on a lazy loading and other fetch strategies that have been it supports and lastly would like to mention that even if you don't specify any kind off Brett stategy in here. Depending on the type of relationship happen, it is actually going to default defense strategy to a the lazy or eager. So when you have a single entity that has to deal with many entities are many objects, like when you have one to manipulation, then sure, when you're trying to display this, we want lazy loading. So have been eight. The fall defects stategy Too lazy in this case. Same as with many, and you're trying to do something with one of the objects on this end, then we want have a need to default to lazy fat stategy. And when it comes to many to one mapping, many entities will have mapping with only one entity on the other end of the relation. So there's no real need off having touch type lazy in here, and same is the case with 1 to 1 relation. However, if you define your mapping, I'm in your annotation on the other end of the relation. Then it's like one to manipulation from this side from right to left. In that case again, we want the fit stategy to be lazy. All right, that's about it. Hope it made sense. So you assume 29. 0801ListAndSetMaping: in this video, we're going to take a look at how we can map Java collections, inhabit Nate, and specifically, we're going to talk about the collections list and set we've already taken. Look at how we can manage relations in have been eight, and in order to maintain the relations we had used collections like List and Set. But sometimes you may not want to maintain relations between tables, especially if you're using simple types like integer, string, etcetera. For example. Let's say that I wanted to also populate the nicknames associated with each boss. In that case, I'm not using any specialized objects in here. I'm just going to be using list off strings as simple as that. So in this case, I can just simply define the list as you see in here and with the following annotations and in order to tell the have been eight that we're using the basic type like string way to provide the sanitation element collection. And in addition to that, we've also provided this particular annotation collection table, and this is going to be a new table where we can see the mapping between the boss and his or her nicknames, and we've also specified the sanitation joined columns. And in here we just specified one column and disk responds to the boss i D. And finally, we've also defined a column for this field, which is going to be with the name nickname Silver Illustrated on the program. And then you'll understand better. How things will go in the database and in the main class spread is straightforward. I created a couple off nicknames and added the mass part off one boss entity, our boss object, sir, the boss object committed the transaction and then the get details matter. I'm just trying to simply get the boss object and trying to display. This will result in calling the toasting matter off the boss object. Hence a little Babel to see what has been populated in the database. So let's on the program. And sure enough, we have that part subject displayed. But let's go to database and see what's happening there. So we have these two tables populated. Let's see what's inside the boss table and also in the other names table. And sure enough, by this we can say that boss with I d one is having the following nicknames, So that's about it. And if you want to use the collection typeset, you can do it as well. So instead, off list he would you set as simple as that. And of course, you have to take care off, replacing the same everywhere else, and same should go in here as well. And it would use something like Hash set, for instance, save the file and run the program. The result would be same as the previous one. No difference or whatsoever. But if you want to accomplish the same by using external tanks, then you can use the following tags. And this is pretty much the same stuff. What we have defined as part off annotations in here, pretty self explanatory and the difference between two. I'm in the list and the set is basically the difference between these two types of collections in Java. Instead, you can't have duplicate entries, and I think in our case it would make more sense to use set because it's not possible that you want to write the same name twice, all right, that helps easily 30. 0802MappingMap: okay. We had talked about how we can deal with mapping in case off list and set and the sweet of we're going to talk about how we can map a map, and we also know that map comes with key value pairs. And so we had to provide the same, and the key value pair would be represented as two different columns in the data base. So let's see how it's done again. You have to provide the sanitation element collection. Since we don't have any kind of relation, we're not going to provide one too many, many too many or anything of that sort. We would instead specify the sanitation element collection, and these two annotations in here would just let us give the name to both key and value pairs. So Map Key would be the column name off all the key values that we're going to enter and column as usual. This would represent the name of the column for this property and that put before the values that the provided in here So the main class code is pretty simple, and let us try to run the program and see how things will go so Basically what I've done in here is the second column is going to tell us who has actually created that nickname to their boss. And if you go to a database and a slash DT and here of the list off tables Select star from Bones nicknames. Well, having it has actually created this name since we haven't explicitly provided the annotation, other names. I mean, if you provide the sanitation, then we can give our own name to the gender to table. But since we didn't do so, have been it has done that for us. So let's try to see what's inside this. And sure enough, we have interesting here. According to what we're populated from our main class. You start to run the program with this annotation and make sure that's going to create a table with that name. And sure enough, we have. We now have that table in here. All right, that's about it. See? Assume 31. 0803EmbbededType: in the Sweet, and we're going to take a look at how we can map a competent in have been eight. Imagine a situation where you have a list off employees and each employee would have a particular address. If I want to design the database for the same, I would have an employee table, and I would also have a table to store off the list off addresses and these two tables will have 1 to 1 mapping, so I'll have a foreign key in the address stable, and there would provide the identify IRS off each employee. Now sometimes adding a new table altogether might be overkill instead of just want to store this object as part of the employee table itself. And for that purpose, we have to make this a competent, not an entity. So if you go to our example in here, I have created this class address and that basically has all these Garrison Serra's with some headdress details. No, taken off the sanitation M Better Bull by specifying the sanitation happen. It is not going to treat this class as an entity, so happen it will not create a table for this class but rather it's going to treat this as a compliment. What I mean by that is if you go to the boss class, which is an entity and will have a table associated with it in the database, we have that address type specified in here, and I've also mentioned the sanitation embedded. So by doing so, whenever I try to create the boss object, I can also pass the address, object to it, and each and every field in here would have a column associated with it. Let me just quickly run this program and then you'll understand better and in our code are simply created an object off the address class. And then I send that object as a perimeter to the boss Constructor. Pretty straightforward. Well, stranger on the program and see the result. And here we are trying to display the boss object. And if you go to the database, it will not have a couple off tables. We just have one single table in here because now that address object is stored as part off the boss table just as you see in here, and each and every field in the address class corresponds to each and every column in the boss table. Hold it. So that's about it. See you soon. 32. 0901MappedEntity: in this chapter, we're going to talk about any hurt and snapping. So far, we had some understanding on how having net map support your class with the relational database table. But how is it going to act when we have opposed your plans that uses Java's inheritance? For example, we have boss class and the employees class. And if you notice we have certain properties in both these classes that are common, for example, regardless off a person is the boss or an employee, the boat will have name and age. So instead of defining those properties in both these classes, what I'd like to do, Rather is create another class a person class, and it would hold all those common properties like name and age, and later I'm going to extend the person class in both these classes, and I'm going to persist. A. The boss are the employees now, depending on the configuration that you said, having it is going to treat this port your classes differently. So let's take a look at a very simple example off the same. So what I have here is the employee class and the boss class, and the only properties that I have in both these classes is the identify rare, and it would be generated automatically. Now. What's new here is this person class and as I've already mentioned, is just simply going to hold like name and age. Now, as your expect, have also extended both employees and boss with the person class, just as you see in here and in our main logic, I just created an instance off. Employees tried to give it a name an age. Similarly, we have the boss object. And then finally, I'm just trying to save these objects into the database. It's on this program and see how things will work. And if you go to the database, we got a couple off tables populated Select star from Boss. Did you notice something? It did not persist. Name an age. Same is the case with employees as well. So what's going on? Let's go back when you're dealing with inheritance in hibernate, you have to explicitly mention how you want hibernate to deal with your inheritance. So what we want right now is we don't want to persist the person class and for the very reason I didn't provide the at the rate entity annotation in here. If I would do so, then having it will actually attempt to create a table that corresponds to person Poggio. But I don't want that to happen. But what I want, though, is I want mapping off. This property is done, but not the class itself. So how can you convey that to hibernate his by providing the following annotation mapped super class by specifying the sanitation you're telling have been eight. That although this class in itself is not going to have a representation off a database table, this class is actually dependent class off other Po Joe's, which will be persisted into a database. So now, having it will actually treat all the properties in here as if they're part off these two classes that inherited Now, if you're on the program, things will work as expected, and sure enough, pretty evil and good. So that's about it. See you soon. 33. 0902SingleTableInheritance: In our previous example, we were able to create an instance, offer the boss class or the employee class, and then when we tried to save these objects, they got saved in the respective tables. And both these tables had couple of properties Are columns that belonged to a person class ? Not this time. Instead of creating two different tables, I just want to create one single table and is off person. And we must be able to create an instance off any off these classes and should be able to persist the details into the person table. So let's take a look at how we can accomplish the same in our person class. Since I mentioned that we want to create a table off person, I have now added this particular annotation entity and have been it is actually going to create a table for this person class, and in addition to that, I've also introduced this new annotation inheritance and I have said this strategy inheritance, type two single table. This is what will help us accomplish what we wanted. So with this annotation, but instructing have been able to create only one table for all this high radical structure . So happen it will not create a table for employees or for the boss, even though we had the sanitation set in here is just going to create one table and that is off the parent class person. So we have now the identify our column moved to person class to represent each record with a unique identifier. Name and age will remain common for both employees and boss test simple as that in our employees class, we don't have the identifier now. Same is the case with boss class, but I have now added a new field in both these classes in case off employees. I'm just mentioning to which boss, does this employee come under? And in Boss Table, our boss entity class I have now included this property which is employed count that just simply tells how Maney employees that work under a particular boss, Tassan Plaza, and in our main class, I'm able to create three instances it belonged to three different classes in here and that I'm just simply trying to save all those objects. So here are the three in stances and then I'm trying to save all those three. Let's run the program and see how things will go. And if you go database, it has now created just one table. And if you do sell it star from person. It has now combined all the fields in the farm off columns and displayed everything. So here is the employer record the boss record on the person to card. Do take a note that haven't it has actually taken care off, adding a new column in here with the name D type. This is called a discriminator column that just tell to whom does this entry belong to? So the first tender in here corresponds to the employees, and 2nd 1 responds to boss object and similarly, the last one. The person object in kids. If you would like to change the names in here and you even more meaningful name, then you can use the annotation discriminator to specify the same. Just as you see in here in the parent class, he would say he would add this column. Discriminator column You would give it some name. What are the name that you wish to Gyu and then the type off the column? Once you do, so you can know add the sanitation discriminative value in all these classes so that you will see the name accordingly. So whatever the name that you set in here would get reflected in this column. All right. See you soon. 34. 0903InheritanceTypeJoined: in this video, we're going to talk about inheritance type joined when you said the inheritance type of joined have been it will actually create a table for each and every entity in the hierarchy . So in here we have these three classes. A couple of them are the child classes off the person class. And so having it will create three tables that corresponds to each one of these classes. And in addition to that have been. It will also create a primary key for the child classes. And that primary key is actually populated with the primary kiss off the person class or dependent class, meaning that the primary key off these two tables is actually the foreign key. That points to the primary key off the parent table. If this all sounds confusing, let's take a look at an example. So what we have here is pretty much the same court as with the previous example. We're trying to create all these three different objects and trying to say the same. So if I run this program and go to the database, you would notice that we have three tables that corresponds to each in every class Of course, let's see what's inside in each one of these classes person, boss and employee. So the person glass has all the objects. And if you notice whatever the fields that are part of the person class are now shown up as the columns pretty obvious and Tim is a case of boss have been it has actually populated its field as a column in here. But as have all the dimensions happen, it will also create the primary key for these two child classes. Are these two child tables, if you will, and actually map to the primary key of the parent class? So in here, the employee count 100 response to the person with I D to which will be boss with a 25. Same is the case with employees as well. This is just a rough example. And even if you go to this entity, classes employees and boss and create your own identify air by auto generating or whatever , it's not going to take any effect because that's how happened. It works when you said this inheritance type two joined. Also note that we're trying to retrieve an entry from the database and in here. I'm trying to retrieve the employees with the I didn't fire too. So that would be this. And when having it retrieves the same, there's going to be a joint operation. So here is the statement to help us retrieve the record. So happened it performed this joint operation. And that's the reason I believe this inheritance type is called Joined. Well, that's my guess. So that's about it. See, assume. 35. 0904TablePerClass: we have one more inheritance type to cover and that is stable per class. Just as the name suggests there's going to be a table associated with each and every class in the hierarchy, and in addition to that, each and every table is going to be independent off each other. That means there won't be any kind of relation between these tables with a foreign key or anything of that sort. Every table will have all the columns. The person table will have the columns for all these fields, like I d name and age and the employee table will have the column boss name and also the columns that it inherits from its parent person class. So the employee table will have these columns in here, including the identify Air has. Alas, this same is the case with the Child Flats boss. The boss table would have all the fields off, parent and and also the properties that are part off the boss class. It's as simple as that that's on the program and see how things will work and go to the database. So its star from Boss, our first let's take a look at person table So you have personality those fields. The boss table will not only have fields in the boss class, but also the fear is that it has inherited, including the identify air. And same is the case with employees as well. As simple as that. And when you're trying to retrieve, are getting object from the database like we did here, it's actually going to simply use the select query on the particular table. If you're trying to retrieve person object, then select Query is going to be on the person object. No joint operation or anything of that sort. It's pretty straightforward. All right, that's it on this video. See you soon. 36. 0905GoodPractices: okay. We had some understanding on how having it walks with inheritance. Now let us take a look at some of the good practices we can follow while working with inheritance. First, let's talk about this term polymorphic behavior. So what I have here is the pretty much the same example. I mean, I'm still using table per class strategy. Now what I have here is I'm just trying to create an instance off all these three classes that are in the hierarchy, and I'm just trying to save all of them. And here is how it looks in the database, just as you'd expect. But let's take a look at what's going to happen. But I try to display the person object so in my cord while I'm doing here is I'm just trying to retrieve all the person objects into a list, and then I'm just trying to print that list of objects. Now, this is not only going to print the person object, but also it's up classes or sub objects that includes employees in boss as well. And here is they find a lot put and, as you can see, were able to display all of them. Now that is partly Morford behavior, because in the scales, person object is having a polymorphic behavior. I mean, a person could be a boss, or he could also be an employee. But sometimes we just want to display the person object, not it's child objects. In that case, you can switch to other strategies. One example that I can think off is you can have a uni directional 1 to 1 mapping from the parent class, which will be person class to one of these child classes. Their bacon Just display the parent object. Are the child object as you need, or, alternatively, concerns to other inheritance strategies. You have to take that call. Now. Let's talk about inheritance. Worse is composition Well, It's basically the difference between hazard relation and easier relation. So in here I have employed class and the boss class, and the boat will have address. Now we can see that employee has the address and boss has address. We can't say that employees address or bosses address, so it has a relation. When you have a has their relation, it makes lot of sense to use a map entity than other inheritance strategies On the other hand, if this was a person class, then what we have here is and easier relationship with this two entities that it makes sense to use other inheritance strategies like, for example, joined inheritance, stategy, etcetera. Because if you use mapped into in this case, then you would end up feeding all the details off person in each one off these tables and thereby at little point of time. If you'd like to retrieve all the person details, you have to write a very complex query, and it's going to drain bit off a performance so we don't want that. So depending on your need, you have to take the call. Let's talk about the single table. One of the good reasons why you want to use the stategy single table stategy is it will help you with better performance because of one good reason. Everything will be represented into a single table. So there, by when you're trying to get the details from the database, or when you're trying to do something with these objects, then there's no need of performing this complex squares like you're seeing in here. So here, in case off other inherit and strategies. Women of performing complex SQL queries like unions joins etcetera. They often demand quite a bit off performance. And for high end applications, this might be a concern in some cases. So in that case, we can use this, and the queries are going to be pretty simple, maybe with just a single set up query you can do to the data that you want. But on the downside dough, when you have all those columns mixed up, you can't really put annul constrained because some of these columns are going to have now values. And we've seen that in our example when we had talked about the single table stategy. If you have a new child glass introduced, then table would change accordingly. There's going to be new column or columns added to the table, and just off the objects may not be supporting those columns so it can cause problems in terms off data consistency. So you have to take a call on though you want to compromise on data. Consistency are the performance and accordingly you to choose the stategy. All right, I hope it helps See you soon 37. 1002FirstLevelCacheExample: hold it. Let us take a look at an example off post little cachet. So what I'm trying to do here is I created the employee object, created decision, begin the transaction and then I'm just trying to say that employ object into the database . So what this is going to do is this will make a copy off this employee object or rather, its data into the second level cache that responds to this particular session. And then it will persist. Or have been it'll purses the data into the database. So after I commit the transaction and before I closed on the session, I'm trying to check to see how many fetches have been done from the database. In this case, we're not trying to retrieve the data from the database, So this is going to show us the count zero. And by the way, in order for this method to work, you have to introduced this particular configuration in your conflict file. And once you do so have been, it will be able to display some statistics that will be useful in our example. So now, if around this program I'm expecting this particular instruction to display zero. And sure enough, since there is no data best fetch operation, I'll read operations to count is zero. And if you notice we don't have any select query in here pretty obvious right now, let me try to do something different The right after I commit the transaction and before I close on the session, I'm trying to retrieve the same employees object, using the identify air, and then I'm trying to display his name. Now this step is necessary because taken note that we're trying to load the object which will not Lord the actual object, but a representation off it are a proxy object. We had already talked about it. So you need to do something with that object in order to first the employees. So now, in this case, happen it will not trust the employees from the database, but rather from the festival cash off the session. And that's what we've talked in our previous video. So if I run this program, we're going to see the employing name. But still, the fetch count is going to be zero. And this explains now from another method. Have you tried access the same object from a different sessional together. So I go to test to method. And in here I'm just trying to retrieve that object are rather, Lord that object. So this time in the scarce since this is a new session altogether, there's going to be new cache memory associated with the session. And the first thing that you're doing here is to load that employees object now happen. It will check to see if that object is present in its cachet, and we know that it is not present. So happen it will not fetch the details from the database, and so we should be able to see the count as one. So let's on the program. And I want to keep this method actor as well because we want that entry to be added into a database because in our conflict file, I've said this to create that there's going to be a brand new scheme every time. So we want to populate some data before we try to read the same. That's on the program and see how things will go. So this is going to be one, and sure enough, there is one fetch operation, credible and good. Let me try to repeat the statement in here multiple times. Not this time. Let me give a different name. These two instructions will not result in fetching the employees from the database, because after we executed this instruction, we have our employees. Details present in the festival cash off the session. So still, the result of the statement is going to be one. So no matter how many times you read that object, there's just going to be one single data best fetch operation. Let's run the program. And sure enough, it's still one, but were able to retrieve the object three times, So this will certainly contribute and improving the performance. Now let's try to do something different. So before I try to fetch the same object, let me try to evict this object so I'll do session. Not effect now, its employees. So what the statement does is it will take all this employee from the cashing, and that's the job off effect. It is going to remove that object from the cachet. So let me try to run the program. And this time, as you might have guessed, this will result in one patch operation. And since we've removed the object from the cash as well. This instruction would demand another database Request two fresh the employee details. So this time the count is going to be too. And sure enough, it is to a simple as that. And we have a couple off cell queries populated. So second level cache is pretty nice feature and you don't have to do anything with it. It will all be taken care by have been it. And in fact, you can't even disable it. It is enabled by default and you can't change it. All right, we'll continue from next video hold. It will continue from next video. See you soon. 38. 1003SecondLevelCacheAndEHCacheConfig: we had already talked about first level cachet, and when I said First level Kasher, that means we have another level off cash. A present in have been eight, and that is second level cache. But unlike fossil cachet, which comes by default and you can't disable it, second level cache ER has multiple implementations and you have the option to choose one. The one that I'm going to use and also the one which is very popular, is yet cash. So we're going to leverage the functionality off second level cache A by using yet cachet implementation. But the main difference between these two cachet is that the first level caches coped with in a session, and all the objects that are going to reside in the festival cachet will have the life off a session. But we're our second level cache, scoped within the session factory and all the objects that are going to be present in second level cache A can be accessed or visible to all the sessions that come under that session factory. So let's take a look at a very simple scenario off persisting a data and then retrieving it . Let's say that you're trying to store the employed data so you would create a session and you would call session, not save to save the employee details. So a copy off objects data will be copied not only in the first level cachet but also to the second level cache re before it gets persisted into the database. And then when you're trying to retrieve that object from the same session, since that object details is present in the first level, Kasher itself, the object or its details or its data will be retrieved from this festival Kashgari that corresponds to the obsession. But if you're trying to access the same object from another session, then since that object is not present in it festival cachet, it will go and take a look at the second level cache. And in our example, that object is indeed present. So it would fetch the object data from the second level cache so it doesn't have to go all the way to the database and fire a query to get the employee details. So this is going to affect positivity in terms off application performance. So let us take a look at steps and mold and configuring the second level cache A. Also, we're going to take a look at the very simple example. So here are the steps first off, which is to include all the libraries that are required. And in our case, since we want to use the each kasher implementation, we're going to include the following dependence in or maven project. And once you include that, do make sure that you may have an update the project so that the respect to libraries will be present in the repository and optionally. If you'd like to get a little bit off control on the second level cache A or if you'd like to make changes to the default configurations, then you can also include the following dependency, which will enable you to do some customization on the second level cache. And when you're including this, you can also include the sex Immel file with the exact same name, yet cachet where he would provide all the list off configurations required, and in addition to that, in order to actually enable second level cache in your application, you have to add the following properties in your Cabinet XML file or, if you're using Cabinet properties file, Then you have toe add the following key value pairs. These two are essentially same. So by this property or just enabling the second level cache A and you're providing here the implementation off second level cache A. And finally, we're also enabling acquitted cash which will take a look at in later chapters. When we talk about Cabinet query language and finally for all the entities that you want to be part off the second level cache A. You have to provide the following annotation catchable that will make these entities qualify for second level cashing. And in addition to that, you can also provide the conferences stategy by providing the sanitation. We're going to talk about conferences, stategy option, incoming videos. So let's go back to eclipse and take a look at a very simple example. So I have the exact same code as previous. The only difference is I have now added this particular statement and the just print total number of hits to second level cache memory and off course. Whatever the things that I had mentioned as part off this file, I have incorporated them. We got dependencies in the bomb. The XML I also have those configurations set in the Cabinet file or if you have a different name, whatever it is. And in addition to that, in the only entity class that we have, employees have included these two annotations, and that's all there is to it. Now let's take a look at what's going to happen when we run this program. So first of all, we're calling this method test within which were just simply persisting the employee details just as you see in here. So while this employee is getting persisted, those details will be copied to possible cachet of the session and then into second level cache A and then into the database. So since we closed on this session right here, we've also lost the first level Kasher that corresponds to the session and in or test to method are treated another session, and then I'm trying to access that object. Or rather, I'm trying to load that object now. In our previous example, this has resulted in a select query to the database. So we got that object from the database as it was not present in the first level cachet off this session. But this time since the objects did has also saved in the second level cache A. This instruction would result in retreating the employee data from the second level cache, and there is no need to send a request to a database. And while we're trying to retrieve the data from second level cache A, it will also copy it in the first level. Cash off the session. And when we do session, not evict, we provide the object. Then it's going to remove the object from the session cachet, but not from the second level cache. So even this instruction would fetch object details from the second level cache. So ultimately, I'm expecting number off entity fetch count to zero that there is not going to be any data that gets fresh from the database. And this should result in value to, as they're going to be, a couple of hits, two second level cache. Let's on the program and see the result. And sure enough, we have the expected output. All right, we'll continue from next video 39. 1004EhcacheExampleProgram: Okay, let us try to get some more inside off which cash Each cash comes with some default settings. But in case if you'd like to provide your own customization, then you can introduce this file each cash dot xml make it part of the list off resources in your project. And once you do that, you can provide your customization and in orderto all right, all the default settings. He can use the stag default cachet and provide your customization. So here we have some customization. As an example, we have said this Param Eter timeto idol seconds to 1 20 seconds. That means if an object remains idle for want of the seconds then habitable deleted state are from the cachet. Similarly, we have time to live seconds. This will be the total life often object in the cache memory. Similarly, we have host off other configurations we can set, and similarly, we can also get more specific and provide customization at entity level as well. So in here were just pointing to the employee class and we have provided some customization . So when you're dealing with employees entity, these settings will have priority over these, and moreover, you can actually create your own context. Good. Some name and use it in the code, an example of which can be seen in here. We have this file each cash a test. I'm going to make this part off this project so that you can take a look at it as well. And so what we have here is let me just come in this out, are created an instance off, cash a manager, and do take note that this is part off each casual library. So once I do that, I'm going to use that object to get the existing cash a context. And here I can provide this name in here, whatever the name that Ugo same goes in here and all this settings that we have in here are no applicable in our program. So here's a quick demonstration of just added some additional configurations and whatever the configuration that I set through program will have the preference over whatever I said as part of these And as of all the dimension, the data that gets stored in the cache A would be in the form off key value pair, so I've just added key value pairs in this way. So I just kept it simple by adding string type key value pairs. One corresponds to apple to two banana, etcetera. And I'm trying to get the data or devalue by using its key just as you see here. And then I'm just trying to display the same. And in addition to that, the cash object actually offers light off methods we can use off just to demonstrate one off them. Her made us off this method, his element on disk. So this method will actually tell us whether this element is present in the disc are in the cachet. No case it is present in the cashing out in the disc. So let's on the program and see the output. And sure enough, walked well. And then guess if you want to create a cashier on the fly and not rely on these XML documents, then can just simply do that by calling this method Add cachet and you would provide your own name. And from this point, you can just use this cash and things will be seen. So the final project that you download from this chapter we'll also include this file so that he can experiment with it. All right, See you soon. 40. 1005ConcurrencyStrategies: whenever you enable the second level cache. A. You have the flexibility to choose the conferences strategy for each and every entity that is catchable. We have a handful off options available to choose from and went to choose the one the picture needs. So let us try to explore all the list off options available. The first off, which is read only stategy. When you said the entity to read only Stategy, then that means we are sure that there won't be any updates on that entity in future. As an example, say that you're trying to store all the list of countries available in the world so that table would have couple of feels. One is the ad and fire, and the other is the name of the country. It is very unlikely that somebody would change the name of the country, and so it's very unlikely that you want to make it. It's in the table, so it's safe to assume that we're going to perform only read on the operations on the table . That being said, we will be able to add the objects into the table and retrieve them, but not make any updates and guess if you're trying to make any updates on this entity than happen, it will throw an exception. That's because when happen, it fetches the objects off this entity from the database and stores it in the second level cache A. It stores it in such manner that we can't make any updates to it. And in here we have said this stategy to read only, and that means we can perform any updates on our employees objects if I try to do that. So in here of just 50 employees object and then I'm trying to make it. It's to it. Let us try to run this program, and he would see an exception. And sure enough, we have an exception. And that, say's Can't Update read only object. So that explains so clearly in case off employees, this is not the strategy that point to choose. So let us start, explore others and see which one fits in here. The second strategy is read, write, and this is apt in case if you're going to do a lot off updates in your table. This option also ensures data consistency when multiple transactions are trying to play with the same object. Let's say that you have couple of transactions T one and T two and they both are trying to access the same object with this read write strategy. The first transaction that gets the object Well, let quite a lock, and the other transaction cannot access its data in the cachet, but rather it would access directly from the database, thereby it would get the latest data from the database in case of the sounds confusing. Then just keep in mind that when you're trying to make a lot off update in your entity, then you want to use the strategy. And clearly this is a strategy that went to use and gives off our employees entity. Next comes the non strict read write, which is equal in to read right, But the difference is it does not really ensure any kind of data consistency. That's because in this case, there won't be any locking mechanism are the operations is performed in Essen, Cronus manner, and so there is no surety of the data consistency. You want to use the stategy only when you know that you're going to make minimal amount off updates on the entity and even in case off get inconsistency, you can cope with it. Has an example say that you have a table called address and you're storing all the addresses off employees. It's pretty rare that you want to make changes to that table because not very often everybody changes their address. And also it's very unlikely that couple of transactions want to make updates on the same employees object. But even if that happens, the data inconsistency shouldn't lead to a serious problem. But you may argue that to be safe, we better use the read write strategy. Well, the answer is no. In some cases, this might be the ideal option, because if you chose this stategy, then there is the additional overhead off, ensuring the data consistency and thereby it will degrade the performance a little bit. So you don't want to use the stategy unless you really need it. The last off, which is the transactional stategy. This would come into picture when you're using JT A or Java transaction FBI, which is well the Java two Enterprise edition specifications for managing the transactions . It's an optional thing that you can use with hibernate and guess if you're using and your performing lot of transactions, then this might be the ideal option. So the data from the database would be fetched in such manner that it would be ideal for performing transactions. Otherwise, you can go with the other strategies we also have on most allergy. It's not really a stategy. It's an option. And it is none. That means they're just simply dissembling an entity from being part off the cash. You can see all that is stuff options in here and here they are. All right, See you soon. 41. 1006NoteworthyPoints: Okay, let us take a look at some of the northward. A points based on the things that we learned so far. The first off, which is cash, doesn't store the objects, but it's data in the form off key value pair, and we start off, although he talked about it. But for the very reason you have to access the objects data by using its side and the fire . Because the key in the key value pair is the ad didn't fire off that object, and you have to use the identifier but not anything else. Also, you can't use Cabinet query language to leverage the functionality off cachet. If you use Hatch you'll, then things will be fetched directly from the database. And even if you use identify where to fish the data. The data would be fished from the database. For example, if you use SQL Statement like Sylhet star from employees, where ideas a call to to then even though there is an object present in the cachet, but that I didn't fire. The select query would be fired in the database to get the data, not from the cachet, and Justin gives If you're wondering the second level cache. A would stay updated with the latest modifications in the database, so it just simply keeps updating itself with the latest data in the database. So if you have multiple sessions trying to access the same object and one of the sessions, make an update off that object and it stores the data in the database, then the cash it would be updated with the updated data in the database. It's as simple as that. If you manually make an update from the database, then the cashier won't be notified to keep itself up to date. And that's the reason. As a rule of thumb, you don't want to really mess with the database directly from its console because that may lead to a lot off inconsistencies and only when you're sure of what you're doing. Do you want to do that? But Justin, because if you mess with it and you feel sorry, then you can just clean up the second level cache A by writing a piece off code. The session, not refresh, will update the first level cachet, and you want to use this method, especially to handle some data inconsistencies associated with Foster. Will cachet, for example, say that you have a couple of sessions and they both read the same object? One of the session writes the object back to the database, but still, in the second session, we may have the old data. In that case, you may get an exception saying that you have a stale object exception. In that case, you can just do session, not refresh. That would fetch the fresh data from the database into the cachet, and you can repeat the same operation. Whatever you're doing in that session, it's not recommended that you do heavy and time bond operations in a session because the first level cachet to a session would be very limited, and that may result in some are off memory exceptions by default. When you make an entity catchable, it doesn't mean that it's collections would also be catchable. You have to explicitly mention it. A sample code is seen in here. You have made the entity catchable, but then you have 12 minute relation in here, but the employees and so you also need to specify the cashing stategy that corresponds to this collection as well. So that's about it. See you soon 42. 1101HQL: in this video, we're going to talk about hedge school or have been it quickly language, just like we have sq. For a database. We have Hetch Grill for Happen eight. But the difference is Eskil is specific to a database. But whereas Hetch Grill is not, let me explain you what I mean. For example, let's that you're using a skill in your code and at little point of time. If you're switching to a different alternative database, then you also need to make addicts in your SQL statements. That's because this in tax on the SQL statements differ from database to database. But where else, if you use have been it query language, then regardless off the database, things will work smoothly. You don't have to make any a bit in your hedge girl statements. That's because with Hatch you're you're not really interacting with the database, but you're interacting with the hibernate framework and Harbour Net framework is actually going to take care off, converting the hatch Grill queries into database specific SQL queries. And that is possible due to the dialect that you can figure in the Cabinet conflict file in case if you're using multiple databases, then you would have multiple have been in conflict files, and depending on the database that you're using, you can specify its specific dialect. So let's take a look at a very quick example of the same. Here are the examples off using hedge school. So with this statement, I'm just simply trying to retrieve all the list off employees present in the database in the employee table. So in here, I don't have to write Select Star from employees like we do in a skill you can just say from employees. And rest of the statement is assumed implicitly by have been eight. If you wish to use the select keyword, that is fine as well. Once you have this query in the form off a string, you have to feed that string to this method that belongs to this session. Object. So you would say session dot create query and then you would pass in the string. Once you do, that, dismantled would return the actual query, object and even just call quickly dot get result list, which will execute that query in the database and get you back. The results, which can be stored in the list, and you can use the list as you wish. Quite boys. We have another example in here that uses Aaliyah's So I said, Select he dot name from employees. So in this case, we haven't Elia's for the employee table, and that is with the letter e down the line. If you're trying to use this employee entity, you can just use its Elias name E and rest of the code will remain same. Do take a note that the employees in here corresponds to the class. Name off the entity. This is not going to be the database table name has evolved. We mentioned were not really interacting with the database, but we're letting have been it, interact with the database. So when you're using have been it, you have to use the object oriented approach to interact with the database, and that is one off the plus sites off. Using Cabinet query language. We Java developers will be comfortable using it because we're interacting with the objects or entities, not with the database tables, an example off where clause can be seen in here. There's a set off example statements. So in here I'm just trying to select employees with the name John. And in here I'm just trying to select all the employees that belong toe a particular city. And in here I'm trying to use the Elia's he that represents employee table. And here I'm just trying to select all the employees. Host City is not set another, and here I am, trying to combine our get results based on couple off tables are entities. I'm trying to use Elia's in this case as well. So what I'm trying to do here is I'm just trying to select list off boss objects that has the same name as with their employees. We're going to take a look at an example of the same in a second, and here is the order by clause. We know what it is. Let's take a look at an example of this in the clips. So here we have the one to many example that we had talked about. One boss will have multiple employees, and in the test class, I have added couple off employees, one with the names under and the other with the name John. The name of the boss is also sunder and in here when I'm trying to display the boss details . I'm trying to sort them in descending order. But let me pick this query from here and let me try to change this to E m. P. Now this corresponds to the name of the employees. If you take a look at the employ entity, he MPs for name of the employees, let me quickly run this program, save the file and let's see the result. So we have the boss whose name is Sunder because he's also having an employee under him with the same name. So likewise, we have many queries that we can run by using Hatch Kuol. But I don't think it's a good idea for me to waste your time in walking you through all the hatch kill statements. If you're taking this course, then I assume that you know s Cuba. This index off fetch girl is more or less similar to SQL just like we have joins sub queries, unions etcetera in SQL we do have the same stuff in hetch kill as well and the syntax is more or less the same. So I don't want to waste your time in discussing all the things that you already know. And as of all the dimension Hetch Grill in terms off sin, thats is more or less similar to SQL. And you can go to this link, which is the official link. And this has pretty much all the types off queries you can use using have been eight pretty easy stuff. So that's about it on Hetch Kuol. I'm going to save this document for you to download. It's with the name Hetch Kildare dogs. You can take a look at it. 43. 1102HCQL: in this video, we're going to talk about criteria, queries, criteria. Query is just an alternate away to manipulate the data in the database. I mean, whatever you can do with the other hatch, kill our SQL, you can pretty much accomplish the same using criteria query. But there is one primary advantage in using criteria. Query. We're going to talk about it in a while, so let's think about the following scenario where you have these two tables in the database . One is the boss table, and it corresponds to list off employees. That means we have one too many relation from boss to employees, and similarly, we also have many to one mapping specified in the employee entity. Let's take a look at the code and see how it would look. So we have the Boston Duty and whispers fire one too many relation with list off employees , and similarly, in the Employ entity, we have specified many to one mapping with a boss object. So it's bidirectional mapping that goes from both the ends. So now my task is to extract data from these two tables, and let's say that this is my task. I want to display list off employees whose name starts with E M. P X and who's boss is Sunder. I also want to order the results that in descending order how can we accomplish this using hatch creo r sq Uh, I would have to follow the following syntax. You would say select and then you would specify list off feels that you want to select In this case, we want to select the employee name, his salary and the boss name that corresponds to this employee from the boss table. And we're going to use the keyboard from to specify from which table or tables We won't extract the data. In this case, we won't extract the data from two tables and so we have to use the joint operation. So we're performing the joint operation between the Boston Duty and the employees entity or table by default. When we say join, it's going to be in our joint. And after we do that, we can now specify our list. Off closets are conditions using this key would where so here he would specify all the list of conditions like on what basis do we want to join these two tables we want to join these two tables based on the foreign key. I mean, based on the B i. D. In the boss table and boss i D, which is the foreign key from the employee table. Once we specify that we can now specify the like condition. So we're trying to list on all the employees whose name starts with E. M. P X. And then after that we have one more condition is to further filter the list based on who their bosses in the scarce. We're trying to extract all the employees who's boss, eh, sunder? And finally, we want to order the list in descending order. Well, this is how you would do either by using hetch Grill or rescuer. But the problem with this approach is that if you make any mistakes, for example, if you say instruct from you would say from or whatever, if it is some type of error, then you would get to see the error during the run time and imagine that you have a very large application, which takes a while to build, and then you have to deploy that application onto the silver to see the exception instead, It would be a lot better in case if you're notified with the error during the compile time itself. And another problem with this approach is as a job, a dollop. Er, you didn't find it. We're in to to to write a query like this. You would rather prefer to interact with the Java objects and methods rather than having to learn a language like SQL or Hetch kill and do a lot of Google research before you figure out the query like this. So the answer to these queries is criteria query. And here are the list off steps that I've listed down, which will explain how we can use the criteria query. So the first step is to create so called value object. Now, this is something new, and we haven't talked about this so far. So what is the object? Well, it is essentially same as oppo Joe, but it does not have any representation off a relational database table. But then why is it there? It is there to hold all this list off values, So the results said that could get by using criteria Query would be in the form off in stances off the value object trance. So this value object class is going to hold all these properties along with a constructor. First, take a look at the value object and see how it looks in our kids. We want to display this tree fields. So one is to hold the string. The employee name and the other is to hold the salary and then one more, which is also going to be a strength to store the boss name. So here is the value object we have and those three fields in here, and along with that, it's mandatory the tune to specify the falling constructor that's going to help us populate these fields. If you don't specify the constructor, you're going to see an error. That's because having it is actually going to use this constructor to give values for the instances that gets created on the fly. So once you have this value object class ready, we can move on and create our criteria Equity object, and it would specify list off entities involved to generate their desired result. Through this, take a look at the code. So whatever we have in here, I mean, asked for the project This is similar to our bi directional mapping example, but this is the code that does the magic. So first of all, in order to acquire decried equity object you to first acquire so called a criteria builder and that you can get a day from session are from the entity manager object. We're going to talk about entity manager incoming videos, by the way. So you would cessation don't get criteria builder, and then he would say, corrected a builder, not create query. And then you would pass in that value object trance. So, by the statement were telling, have been eight that we want the criteria equity object. And we want to use this value object class to store the results. That and enough to that, you'd have to specify list off entities involved to generate the desired result. And the way you go about doing that is by defining the route object off each entity. In this manner, they would say criteria query dot from So, just like we specified the keyword from in here as part of the SQL query. And then we mentioned the list off tables involved. We're going to do the same by using this method from and we specified list off entities involved to get the desired results. That and internally, these two instructions would actually result in performing the joint operation off. These two entities are tables. So with these two instructions, we're also going to get so called their route objects using these objects, we can actually get access toe their fields and we're going to use their fields and the rest off our code. So the next step is to apply the restrictions dislike were doing in here. We have set of restrictions are predicates are were clauses in order to filter out the results that we do have the same stuff in our court as well. And just like we have three conditions in here, we have the same stuff in our court as well. Everything is pretty similar. But the only difference is we're doing things in more object oriented manner. So you would use the criteria builder object, and you would call this matter equal to check the equality off these two values. So this is similar to what we specified in here and then in addition to that, we also specified this like claws to see who are all employees or having the name that starts with the MPX just like we specified in here. And finally, we're also checking to see that their boss is Sunder. And once we acquire an area off restrictions, we can apply them by using this method where and you would apply list off those We're clauses. So you would say criteria clearly dot where and then you would specify set off restrictions and after that, he would apply the order by clause, just like we did in here. So here it is. Here's the statement and this time you're going to use the DSE method off criteria builder to order the results at in descending order in which field you're going to use to sort the results. That is what you would specify in here that's by the employee name. And finally you would call this method select and here you would specify everything. I mean, just like we did in here who said select and in these three fields you had mentioned the same stuff we mentioned these three fields and in addition to that, you also need to specify the value object using which the results that would be stored. So until this far you have constructed the criteria query, which would essentially represent the same Cleary. And after that you have to take care off. Executing the same. You can do so by saying session dot create query and then you would pass in that criteria quickly as an object. So far, we created a hedge bill statement, which is a static string and would pass it as an argument. But this time we're passing the criteria query. And finally, we're just trying to display the results set so this on the program and see how things will go. And sure enough, you have the result. As expected, I'm going to make this project about bull for you to import so that you can play with it. Now let's say that I wanted to apply one more clause that only the employees whose salaries greater than 1500 I want to display. So we just have to simply apply on more cross in here. So I'm going to say criteria builder docked. We have another method called greater than you would specify the employee's salary field in here salary and you would do the number which will be 1500. And that will do so out of this. To employees that got populated, we would see only one employee, and it's going to be this because only his salary is greater than 1500. Let's run the program again. And sure enough, we have the result as expected. So that's about it. On the criteria query. It is useful because all the Java developers would feel more native. And they're more comfortable in writing code in object oriented approach than having to learn a new language like SQL. So whichever way you find comfortable, you can use it. Both are preferred, and they both work very well. All right, that's about it. See you soon. 44. 1103NamedQueries: and the sweetie we're going to talk about named queries. Let us say that you have the following hatch kill statement, which would help you fish the employee with a particular name. Let us also assume that you're going to use the sexual statement across hundreds of locations in your application logic. Then you would likely face a lot off problems because if you were to make any changes to this query, then it would have to reflect across all the locations and the sad part off it is there is no syntax highlighting. If you forget to change in one location, then you're going to face some inconsistencies with your application behavior. And as a by product, there's a high possibility off getting run time errors as well. It can easily miss up with the syntax off the Hatch Girl statement, and in addition to that, there's a lot of physical effort involved to incorporate the same changes across all the locations and is, of course, a terrible waste off time. The solution is named queries, so essentially what we're going to do is we're going to give a unique name to this query, and then we call it and named Cleary. And from that bind, wherever you're using this query, you can just use its identify air or its name instead of writing the entire query, and then you'll get rid off all these problems. Now, this is something similar to using a variable. For example, say that you have a very blacks and it holds a particular number. Now insert off writing the entire number beverages needed. You just simply going to use this variable everywhere in your application. So that would essentially solve a lot of problems like this. Same is the case with a named query from this Take a look at how it's done. So here we have the employees Poggio or the Persistent Class and on top off it. Since this named clearly belongs to the employee entity, I have defined the named Cleary in the same class, and it is how you would define it. Isn't these annotations task simple as that, and the sanitation expects you to do this too obvious para meters One is the query itself and the name that you want to give to that query. So here we have this query and we're trying to select the employees based on a particular name. Now, when you use this colon in here that will allow us to do so called a placeholder. That means whatever is written in here can be replaced at later point off time from our court. And we're going to take a look at an example in a second. So here is how you would define the named query. And once you do so, you can access that named query by saying session don't get named Cleary and you just simply passing that name. So this would fetch this query from here. And once you do so you can set the perimeter. In our case, we have one place holder which needs to be replaced, and you're going to replace by using this method, said Para Meter, You would specify the name off the placeholder, and he would give you a value. So in our case, we're trying to fetch the employee with the name E M. P X four and we'll see the result. And here it is, but it's simple and straightforward. All right, see you soon. 45. 1201Transactions: in this video, we're going to talk about transactions and have been eight. We had talked about transactions in detail in my database course. If you want to check that course, I have put the link to that course in the final chapter off this course. But for the sake off this course, and in case if you don't know what is a transaction, then here is a quick example of the same. Let's say that you have a banking application and see that there are a couple of customers A and B A holds the total amount off 1000 and same is with the B. Now let's say that a wants to send 500 to be. So here are the sequence off actions you would take as part of a single transaction, so you would basically didn't find it from his account, and then you would credit 500 to bees account. So if you're performing this kind of task without using the transaction mechanism, then this is going to yield a lot of problems. As an example, say that after you directed find it from his account, there is an exception in our code when there is an exception. All the rest of the lines was not be executed. And that includes crediting by wonder Toby's account. So we're going to see is a count as 500 and bees account would still remain as 1000. That is clearly a problem. So if you use transaction mechanism that would fulfill all these transaction properties. So let's talk about all of them at Thomas City insurers that all the sequence off factions involved in a transaction will take place or none at all in case off an exception. And that is certainly a good thing to have. For example, if we have an exception after deducting finder from his account, then none of these actions should actually take effect. Everything should be rolled back to their original state. So still, the values should remain to be same, and data consistency insurers that after performing the transaction, the data is inconsistent state. For example, before performing these two transactions, the total value would be 2000 and even after you perform this transaction, the total should still remain 2000. If not, then there is some problem and data is not consistent. The isolation defines that each and every transaction should be performed in isolation. For example, we have a couple of transactions, let's say, and the boat are trying to obey the same record in the database, Then only one transaction should take effect in isolation, while the other transition relay, the being waiting state, are doing something else. Durability ensures that when the transaction is taking place, if there is any loss of data in the database, maybe it's due to natural calamities or whatever. That should not impact the overall consistency off the database. So that's what is durability. So together all these properties are called acid properties. So when you take out first letter from all these properties, it becomes the world acid and hence the name. So let's take a look at a quick example off transaction and believe it or not, so far in our examples, we were all very performing transactions. So to begin a transaction, you're going to use this statement session dot begin transaction, and then you would perform all the sequence off past that together can be considered as a single transaction, and once you're done with it, we're going to say transaction dot com It this is what will come with the changes into the database. And in our example, I'm just trying to get the employees object with identify are one, and I'm trying to set his salary to zero. Same is the case with employees with I d to. But in between these two, I'm trying to get an employee, which is basically a null object, and I'm trying to set the salary to zero. So guess what? This instruction should result in an exception. In our case, this is going to be a null pointer exception. So an exception would be caught somewhere in the middle of the transaction. And after it is caught, I'm checking to see if the transaction object is now. And after that I'm calling this Method Transaction Tot roll back. So what this matter is going to do is it's going to reverse everything, whatever has been done since the beginning off the transaction. And that's what we want. We won't roll back everything in case off an exception. Imagine this transaction to be the banking transaction that we had talked about. Then there is an exception. After performing the first task, we won't roll back everything we don't want anything to take effect at all, and that's what I'm trying to do here. Let me try to run the program without having any exception. Everything should work smoothly. Let's go to the database and see what's happening there. So if you go to the employees stable, sure enough, we have the salary set to zero. Now let's try to change your code and make sure that we get an exception. Let's on the program again, and sure enough, we have the no point exception. And if you go to the database, nothing will take effect at all. So that's the beauty of transactions. So these are the primary methods, which are typically used in Harbin. Eight to perform the to manage the transactions. It begin the transaction and come in the transaction. In case if there is an exception, he would roll back. Also taken note that in case if you forget to specify the rollback mechanism, then happen. It is actually going to manage transaction for us and will perform the role back on our behalf, but we can't completely rely on it. It's better that you explicitly roll back the transaction and guess that something is going wrong. So that's on the program and see that nothing would take effect. And sure enough, there's no change taking place. So likewise, we got a lot off other methods that you can access from the transaction object. So in here in the finally block, before I'm closing on the session, I'm trying to see if the transaction is still act to. So this would display a bullion value, whether the transaction is still act or not. But before that, let me just quickly undo and put the rollback statement. So in no case, before we execute the statement, we're trying to roll back the transaction. So this should result in falls, and sure enough, it is set to falls. Similarly, we got a lot of other methods. Not a lot, but quite a few. You can easily understand what they are. Just scroll through all the medicine, see the description and get a sense of what they're doing. Let's try to get the status of the transaction, and it gets displayed there. Okay, let's get whatever the string that she was to give here and on the program. And here's the status transaction has been rolled back. All right, that's about it. See you soon. 46. 1202Versioning: in this video, we're going to take a look at how we can manage data consistency for the concept off worsening. This is applicable, especially when couple of transactions are trying to read the same record and do something with it. Now let us take a look at a real world example of the same. Let's say that you have a banking application and say that you have these three customers A , B and C is holding the total sum off 1000 and say that BNC has decided to send 500 toe is account as a gift on his birthday. Now, under the exemption that BNC did not initiate the transactions simultaneously. This is how the scenario would be. First people transfer the funds. So his transaction primarily in Moore's these two steps so his transaction will read the value off A which will be 1000. And then it will credit the value by 500 would save the total amount back to the database and at later point off time seyval log into his account and we'll also do the same. So in his transaction he would be able to read the latest value, which will be 1500. It would credit 500 to it and then commit the transaction. So the end result is that a will hold the total off 2000. But no, Let us try to understand what would happen if these two transactions go simultaneously. I mean, led to that both B and C has initiated their fun transfer simultaneously. Then here are the steps in mold. This transaction will read the value off A which will be 1000 and same is the case would see now, see has read that value off 1000 before B has modified and committed the changes. So these two transaction will read the same value off 1000 and down the line people at 500 would update the value to 1500 and C is also going to do the same. It will read the value of 500 and upgrade the value to 1500. But unfortunately the resulting valley is not 2000. This is 1500 but still both being see see their account debited with 500 Now, this is definitely not something that we want. So let us try to replicate the same behavior in our example. So in order to illustrate this, I'm using the concept off multi threading. So I have extended our class with the tread class and that will be able to introduce this method run inside, which I'm just simply trying to call this method test. And in here I'm just trying to read the employee record with a particular identify air and then simply trying to update its salary by adding 500. Now, the key thing to note here is that inside our main logic, I'm initiating couple off threads in here just as you see in here by calling this method start now, this is all core java. We don't want to get deep into it. But the point is, I'm trying to initiate couple of treads and assume that we're trying to perform a couple off transactions and additionally have also put this instruction to pause the trade for three seconds so that we're sure that both the transactions will take place simultaneously , not in sequence. So currently the employee value is 1000. So we're calling this method insert before we are initiating these two threads. So the value will be 1000 and after we perform a couple of increments with couple off threads. What is the value that you're expecting here? Well, let's run the program and see the result. So we waited for three seconds on each thread, and ultimately, if you notice we have a couple of updates from both the trends, so ask for you. Would the value B 2000 or would it be 1500? Well, let's take a look at the data base and you would notice that the value is 1500. This is quite wrong. We did not get any kind often exception in here. This is as though what the transactions were successful. But in the end, we have a very inconsistent data. So going back to our example, this is equal into these two years are seeing the success message that their transaction is successful. But in the end, the result is still not updated. So why is this happening? This is happening because have been It is not aware that the data is updated by some other transaction, So we need to incorporate a certain mechanism that would solve this problem. And obviously, as you would guess, the solution is worsening All you have to do is to go to the entity class and introduce a new field and with the name version. And in addition to that, he also have to specify this annotation worship in now. Believe it or not, that's all there is to it. This will solve the problem. But how is it going to solve the problem? Really? Well, let's go back to our example. So this time we're actually going to see a new column in here. But the name version and that column is taken care by hibernate. But what does that column signify? Well, it will just signify the Harbin aid. Whether that record is updated or not, let me explain what I mean. So whenever you make an update on a particular object and you commit the transaction, the object details will be poor sister into the database, and along with that, having it will also increment. It's worsen. So every time you make an update on the object and you persist into the database, the worship will keep on incremental. Now can you try to imagine how is this going to solve our problem off concrete access? Well, it's pretty simple let's say that we have a couple of threats trying to pitch in to this code and the boat with the value off 1000 and along with that, they will also read the washing number off that record. Let's say that the current washing is one, so those two transactions will read the value as one, and they just simply move on with other instructions. Those two threads will wait for three seconds, and ultimately they will make an update on the object. And what come it, the first transaction that will come with the changes. We'll also update or income in the wash in of the object by one. So now the washing will become, too. And then, when the second transaction price to come with the changes hibernate notices that there is a mismatch between the wash in that was read before and the washing that is president now, due to that mismatch happen, it will be able to understand that it needs to fail the transaction and roll back the changes. So that's how it's going to work. It's on the program and make sure this time we're going to see an exception. And sure enough, regard this exception, it say's optimistic lock exception. And if you go through the description, you would notice that is just simply mentioning that there is basically the washing mismatch. So now, at least in the scares, the second user will be notified that his transaction has failed so that he can at least reinitiate the transaction are in your application code. You can write your court in such way that it will re attempt to perform the same transaction. Let's also quickly take a look at the data base, and here is a new column. Coercion or it See you soon. 47. 1203ConnectionPooling: in this video, we're going to talk about connection pooling mechanism whenever you're trying to perform the transaction from your application when the transaction begins, your application is actually going to request for the database connection to connect to the database and perform the transaction in a typical Jedi busy application. I mean, in case you're not using any or, um, tool, and you're just using the GBC to connect to the database, then here is how the scenario would be. Your application would request for database connection to the data source, whose implementation would be provided by the database driver that you use. And the database sores will delegate that request to the driver software, which in turn will try to acquire the connection based on the connection. Perimeters that you provide and ultimately application will be able to connect to the database and perform the transaction. And once the transaction is over, the connection would be lost as well. Well, there is one serious performance problem with this. If you keep on creating and destroying the connections, everyone's a vile, then it is going to cost you a lot off performance, and it will also increase the load on the server, So the solution to this problem is connection pooling. So instead of delegating the request from data source to the driver, the request would be sent two so called a connection pool. Now this is a mechanism which will manage all the connections. So let's talk about the connection pool a little bit. This thing about a real world scenario off connection pooling we can correlate connection pulling with carpooling in real world, let's say that you have the carpooling service, and at the moment you dont have any cars because there is no customer requesting for a car . No, let's say that you have one customer who has requested for a car, so you will buy a car, keep it inside your pool, and then you will start the car, after which you will provide the keys to the customer. He can roam around in the car and come back to the same place when he parks the car back in place. He's not going to turn off the car. He's just going to get down from the car and he goes back home now for the next. Wasn't ho comes in? The question for the car. He would have a car ready and neither you are the customer have to stop the car. He will take the car, which is already started. Hebel roam around. Come back. He would park the car and go back home without stopping the car. Now, in case if the customer ho took the car is still roaming around. Meanwhile, let's it therefore more customers to be sold. Then you will just simply by for more cars start them all and give it to customers. And in case, if you're running out of space and you have lot off simultaneous customers requesting for the car, then you would keep them in the waiting state until the car is made available by other customers. This is how exactly Connection Pool would work in hibernate as well, so you would have a pool Whenever there is a purpose for the database connection from your application, there will be a new connection created to perform the transaction, and this would happen when you start decision and initiate the transaction. Once the transaction finishes what it has to do, the connection will not be closed. It would be made available for other requests and in case if there are a couple of transactions taking place simultaneously, we'll have couple of connections in the pool and each would correspond to one transaction, like, Where's the connection pool will manage all the connections. The advantage here is we're saving a lot of time and performance because we don't have to create the connection and destroy it. Everyone's a while. Hibernate automatically supports the pooling mechanism by default, but unfortunately it is not very efficient and is not meant for high end applications. So for connection pooling mechanism, we have to use a tour party library which especially tuned to sell this purpose off pulling . So let's take a look at an example of the same. First of all, let me prove that having it uses its own pulling mechanism. So for this purpose, you can just simply run any off our previous programs. And if you go to the output and search for the term pool, you would notice that there is already a pooling mechanism taken care by hibernate. But let us take a look at how we can use 1/3 party tool to stop the process. And for this purpose, the many implementations African News. We're going to be using se three p o library to incorporate the connection pooling mechanism the many libraries out there, but this is the one which is popular. So I'm going to add this dependency. And in addition to that, we can also add this. Configurations that are specific to that library, and what these configurations would allow us to do is to do some customization for the pool that gets created on the fly. So by this perimeter, men size were saying that the minimum size off the pool should be five. That means our pool should at least hold five connection simultaneously, and it can grow up to 20 connections by setting this perimeter back size the time. What would just simply means how long should the connection stay idle in seconds? So after waiting for 300 seconds, if the connection is not utilized by your application, then the connection would be closed. The Max statements is simply the maximum number off prepared statements. Finally, we have this perimeter adult US period. This is a little tricky, basically from the database and as well the connection would time out. So what adult a spirit means is happen. It will ping database. Everyone's a while to make sure that the connection would stay active for a two least 3000 seconds. And once you configure this and you have this, dependency added, we just have to update the project ones, though, because this will download all the libraries required. It's going to take a while, so let me pause the video and get back So we're done. And now if you run the program, he would notice that this time the pooling mechanism, his say Threepio. And sure enough, that's the library, which is used. So that's about it. See you soon. 48. 1301BulkInsert: in this chapter, we're going to talk about how we can deal with bulk operations in Harbin aid. And in this video, we're going to take a look at how we can insert bulk amount of data into the database. Let's say that you were given with the task off inserting 100 employees into the database, then it's pretty straightforward approach. All you do is you take each and every employee object and use this method session, not save to save the employees. But what if I tell you that you have one million records? Are one million employee details to be inserted in the database? How are you going to handle that? Well, if you follow this approach, then it's going to cause one serious problem. Can you guess what the problem would be? Obviously, when you're trying to save so many objects into the database, that means all those objects would be accumulated in the cache memory, and ultimately it would lead to out off memory exception and your transaction will fail. So how are you going to handle that? You know that illustrate the same. I'm using the full loop to create employee objects on the fly and trying to save them. Now it is going to take a bit off time to actually insert one million records. So for the sake of this example, I'm just trying to save 40 employees objects. But as UME that this number is one million. So how are we going to handle that? Well, it's pretty simple. All you have to do is you would clear the cache memory once a while. For example, you're going to check to see if we had inserted 10 records by now by using this little math , and if this condition is satisfied than what you want to do, he would cessation, not clear. So what this will do is it will evict each and every object from the cache memory or first level cachet to be specific. So this will not lead to out off memory exception because we're clearing the cache memory every once a while. But we have another problem in here. Let's say that you're trying to make a ditz to the employee object on the fly, for example, say that I want to change his name to something else. Set name to say, employees, new, whatever the name just for the sake of this example. All right. Now let me run this program and take a look at the table in the database. Now, since we're trying to evict all the objects from the cache memory before we said transaction, not Comet, then only until we save the object will the changes reflect. So whatever the objects that come after it will not take any effect at all. It's on the program and see the result. And if you go to the database, you would notice that the employee name is not updated. So we need to try to save the object before we try to evict it. How can we accomplish that? It's very simple. We just need to call another method before we say sessions are clear and that is session dot flush. So what this is going to do is it would force decision to flush. That means all the objects would be persisted with their latest changes. And so that includes this name optician as well. No, that's straight on the program and see the result. And sure enough, if you go to the database, they would see those employees records getting updated. So if you're following the strategy to deal with bulk amount of data and you're trying to clear the cache once a while. Then do make sure that you do session, not flush before you try to clear. Now, if you have second level cache enabled, then you need to take care off, brushing that memory as well. Because even that cache memory has some limit. And if you're not careful, that may lead to out of memory exception as well. So you would say Session, factory, Dr Get cachet And then you would just simply say, evict all. Or we can use this method ev it. And then you would specify the class name that would ever all the objects that corresponds to the class and this should work as well. All right, that's about it. In this video, we'll continue from next video. See you soon. 49. 1303ScrollableResults: so we had. One problem with our earlier approach is that we're fighting too many queries to get the records, so the solution to that problem is scalable results. So what scalable results would do for us is it's just going to fire one single query, and that is to fetch all the records. And those records will not be stored in the cache memory. If that's the case, we would get out off every exception right of a. But rather the results would be stored in the RAM memory. And depending on the logic that you have, those objects would be fished accordingly. So screw herbal is like a traitor, and it would allow us to navigate through all the list of records one by one. By calling this method. Results start next. I can access that particular object by using the statement. So here I'm trying to fish that employ object, and then I'm just simply trying to print them so this would essentially fetch from the memory, not from the database. So this is not going to fight a database query, so that would result in improving the performance. But when you try to keep retrieving those objects from the memory and store them in the cache memory. Eventually it would result in out off memory exception. So you have to take care off, flushing the memory once a while, just as we're doing in here for every 10 the cards were trying to flush to keep things updated. And then we're trying to clear the cache memory as simple as that. So if I'm trying to make any updates on this object, then it would make sense to flush before you clear the cache. So that's on the program and see the result. And sure enough, we have some updates done on those objects. And if you go to the database, things got reflected. Well, okay, let's try to analyze the output a little bit to go back. So here we have the select query, and once we performed, select off all the employees. Amusing sits out statement to display the current employees, and that's the result off this, after which we performed the update on that object, and eventually we're trying to flush every once a while for every 10 the cards and every time you flush those objects in the cache memory would get updated, so you should be able to see 10 updates in a sequence that go at a time. And every time you try to look through your printing the current object, Tassan Blouse that. But the key thing to note here is you don't find any other select queries is just one single celeb query that does the magic. So that's about it. Hope it makes sense. And I'm going to make this project available for you to download. So inside the project, you should be able to locate these two files test or Javan test to Dar Java. And this file has a scalable results. All right, see you soon. 50. 1401ReverseEngineeringPart1: in this video, we're going to talk about reverse engineering so far in our examples, we were auto, creating the tables in the database, pissed on the entities present in our project. But sometimes you might want to do it the other way. I mean, you may have a database with some tables in it, and you wanted to generate entities for each off the table. This is often the case, especially for using a legacy technology. And now you wanted to switch to an Orem tool. For example, say that you have an application which is using JBC to perform database transactions, and now you have decided to switch to hibernate. It becomes very tedious job to write entities for each and every table present in your database. Instead, it would be a lot better if you use an existing tool that will. So the purpose. That way your code would be less error prone, and you don't have to spend too much time in trying to switch to happen. Eight. So let us take a look at how it's done. So what 1/2 Here is one too many examples that we had talked about, and I'm just simply going to extract it in the folder and then imported in our eclipse. And Roman has a maven project. All right. Now, let me just quickly run the program just so that there will be some data populated in the database. And if you go to the database, we have put this tables populated. Now let me do something. Let me just delete these two entities from here. Now, imagine that I'm using very busy in our application, which is a legacy technology. And now, since I'm switching tohave anade, I wanted to order generate the entities. So before we try to generate it when it install some of the tools required to do this job. So I go to help and then eclipse marketplace. The tool that I'm going to install is with the name J Barstools. As part of J. Barstools will also have a tool which is meant for have been eight. Let me search for it in here and here. It iss let me just install it now. Whatever the promise that you get, just keep accepting them. It's going to take a bit off a time here. Let me pause the video and get back. Let's confirm it. Let's accept the license agreement had finished. When you get a prompt like this, just say install anyway. Now, in this problem, just select all and accept. Let's restock the eclipse. Okay, here we are. Off track lips Country started. Now what we need to do is to switch to the database perspective and create the connection. So let's see how it's done. You goto window and then prospect to opened, respect to and choose other and in the list, you should be able to find database development hit open. Since I've already configured the connection ones, it's shown up in here, but in your case, you need to create one. So you just simply select the state of his connections and then right click hit new search for your database. In my case, it's supposed grass cure, so I would choose that hit next. And here you're just provide all the connection para meters to help connect to the database , and then you click Finish. It's as simple as that, but before you hit finish, just try to test the connection and make sure you get this message being succeeded. If you see an error message. Then you might be doing something wrong in here. Just make sure all the connection Bad image Also correct. Now, once we have it working, we need to switch to a have a net prospect to. So I goto window prospect to and then I search for have been eight and hair It is the habit Prospective wouldn't have been appearing if you have not installed two barstools. So once is like that hit open here. We need to add so called cabinet configuration and is based on the harbinger maximal document we have in our project. So since I've already configured it has shown up in here. But in your case, you need to hit this place icon and then he had to choose your project. So let's choose our project and hit OK. And we chose the annotations option in here Now, Unit data point to the properties file which will be happening, or properties are they have been it. Come, pick file. So we hit set up In case if you don't have an existing conflict file, then you can create one, and you can just simply say very want to store that conflict file. I mean in which folder it next. And then you can just populate all the dead of ex convicts stuff. So once you populate all these and hit finish have been it will create the conflict trial for you in the project. But in my case, the convict pile is already present. So I'm just going to pick the existing one. So I say use existing and then I chose this file. So once you do that hit, apply and hit OK, that would add or configuration in here. So until this point, we have everything to do the reverse engineering and will continue from next radio. 51. 1402ReverseEngineeringPart2: So once you have everything ready, all you have to do is to hit this icon that is combination of Harbin, it icon and the play icon. This icon will be visible only when you're inhabited prospective. So hit this down arrow button that that is next to that icon and kills this option. Happen it cogeneration configurations. And in here you may not see anything, so you have to create one. So you just right click on this happen It called Generation hit on new configuration and here he would choose the conflagration that we had previously set. So let's choose that. And you would provide the or poor directory where the generator entities would be stored So you would hit, browse and choose the directory. In my case, I want to keep it inside this directory hit, okay, And let's enable this option to enable the reverse engineering from database connection. You would provide the package name in here, and I'm going to simply provide the package name. So it's com dot company dot hatch beep Raj. This is the package that I'm using across the project. Once you do that, you would basically select what are all the things that you want export. In my case, I want to choose this option domain code, which essentially means entities, and along with that, I also want to generate have been it XML map ing's. And if you want to gender it, annotations for your entities, then you can check this option. Additionally, you can also choose these other options available. For example, if you enable this, this tool will generate the Dow object. Well, at the moment, we're not really looking to gender, dad. So for now we're going to leave rest of the stuff as it is, and we just wanted to select these two options it apply, so that would save all the details. And that's all there is to it. All you have to do now is it run? It's going to take a second or two or maybe a little more So we're done. So let's switch to our job our perspective And sure enough, we now have those two ended its populated. Let's take a look at what's inside them, so we have everything like a normal po Joe. But where is the relation one too many relation? Well, it is taken care as well if you go to these files. So the boss mapping file has defined a set which would constitute a set off employees. And even it has taken care off, defining one too many relation with the entity employees. And in the employee mapping file, we have many to one mapping. So this is bidirectional mapping from both the ends. Let's take a look at some of the errors we have in the test or Java, so basically we don't have a constructor that just takes in one perimeter. So let's try to add that constructor in the entity. And this is going to be the name of the employees, just simple as that, and similarly went to fix the boss into the as well. So let's create a new constructor in there So string boss name his age and set off employees. So let's try to, I mean just copies and biz them in here. We have a new constructor and this should fix issue, so that's all there is to it. So isn't that beautiful? But before you run the program, since we're using XML conflict files, where to make sure that we have these two file specified in the Harbin It convict file or no case pose Greek symbol file that is under the resources. So let us add those two mapping files in here. Let me just visible this, too, and we will add the mapping XML file. It's as simple as that is going to be boss. And also we need to take her off the same in our main logic as well. But let me just quickly come in dark. All these we're not really interested in performing crowd operations. We just want to see if things are working after we did reverse engineering. So instead of vanity, that class this is going to be hand add class and same goes here as well. And before we run the program, that has also changed the confident here and made this validate. So this will ensure that the entities in our application and the database tables can be mapped to each other. It's on the program and see how it goes. All right, let me stop it. I guess we already have an entity with the particular identify air. Nope, I guess it's auto generated. It's on the program. And sure enough, things worked really well. And if you go to the database, it would see a new boss entry being populated. If you're on the program again, you missy, an exception. That's because I believe there's going to be a conflict. And sure enough, we do have a conflict. So it says, double get key while the while its unique constraint boss. Primary key. So it needs to be taken care. But you got the point. We're able to do the reverse engineering and things are working well, if you want me to fix that, so to fix issue, let us change this to increment. Let's get the word correct. And now let's run the program and save things would be fixed. Well, sure enough, I think it's working really well. And if you go to the database, we do have multiple interests. All right, that's about it. See, you assume 52. 1501EntityManager: so far in our examples, we have talked the bottom of the hibernate specific terms, like session, factory session, havin a dot C of Jadot XML, etcetera. Now these a ro specific tohave, anade but are not part off GPS specification. Let's that letter point off time you have decided to switch to a different or, um, tool. Then it becomes hard to make changes in your code because you have used some have been its specific classes and interfaces. So the better approach is always to use GPS specifications so that tomorrow, at little one off time, if you want to switch to another or UM tool, which also implements GPS specifications, then your job would be a lot easier. But the reason why I had used these have been in terms is to make you understand some of the habit specific concepts, like how the session factory works, how the session work's etcetera but ideally told us a good idea to use GPS specifications everywhere. So whatever we had talked about in terms off hibernate, we pretty much have the same stuff in JPs specifications as well. By the end of the day have been eight implements JPs specifications, and in addition to that, it provides some more additional functionalities. If you want to compromise on those additional functionalities, then you can use these JPs specifications. So instead of session factory, you would just simply replace it with Entity Manager factory, which belongs to J. P. A specification. Similarly, session can be replaced with the entity manager Arhab, innit? Convict file would be replaced with persistence or XML file, and it would have the same convict stuff. What goes inside the Cabinet? Confident, similar as well. And instead of get mattered, you would use find, insert off of it. You would find it match and some of the methods will actually remain common like refresh, closest, clear etcetera. So what we have here is a very simple example that uses only JPs passive occassions. Nowhere in here do we see any habit. Specific classes are interfaces. So instead of session factory, we're now using Entity manager factory, an insert off session. We're not using entity manager and just off the court is pretty self explanatory. And of course, we're not really following good practices like wrapping the court on try catch, block, etcetera. I just want to keep things simple. The idea is just to make you understand how we can use GPS specifications. Instead, Off have been its Pacific stuff. And internally, this is actually going to use have been it specific stuff like Session Factory and to do manager is actually going to use have a net session to do its job. And also note that insert off our binary XML file. We now have persistent or xml file, and it pretty much has the same stuff. What goes inside a habit? Xml file. So we have all these properties to connect to the database Desirable Connection para meters . But do take a note that now the name changes and uses some JPs stuff rather than have been eight packages. But by using persistent or XML file doesn't mean that you can't use any have been it specific configurations. An example off which can be seen in here We can still use have been it library and said this configuration, just as you see in here. Also unlike having a dot XML file, which goes inside the Resources folder, the persistence dot xml file. But go inside meta hyphen I enough directory under the Resources Directory if you're having a maven project, so that's pretty much it. And everything is going to remain same in our entity class. We were already following GPS. Pontifications would induce any have been X specific stuff, and that's about it. Just take a look at the code and try to understand we're trying to begin the transaction doing something in here. In this case, we're trying to persist an object and then finally committing the transaction. We're trying to read the employees, and finally, we're also trying toe removed the employees from the database. So if we run this program, all these actions would take place in sequence. And here is the result. We inserted an employee reading an employee and finally would delete it. That regard It's as simple as that. All right, see, assume