Add JPA Annotations to Entities9:00 with Chris Ramacciotti
In order for Hibernate to map data from our database to Java objects (entities), we'll need to add the necessary JPA (Java Persistence API) annotations to those entity classes.
Git Command to Sync Your Code to the Start of this Video
git checkout -f s1v6
Using Github With This Course
You can complete this course entirely using code created by you on your local machine. However, if you choose to use the code I've made available to you, you have two options:
- Use the project files linked at the bottom of this page, or
- Use the Github repository I've made available (recommended)
If you choose the recommended option of using the Github repository, it can be found at
To utilize Github with this course, you can download the Github desktop client for your system or use the command line interface provided with Git.
Clone this repository to your machine using the Github desktop client, or using the following command:
git clone email@example.com:treehouse/giflib-hibernate.git
To update your local repository to match a video's starting point, you can use the
git checkout command in combination with the stage and video number. For example, to update your local repository to match the starting point of Stage 5, Video 4, you'd use the following:
git checkout -f s5v4
Notice the use of the -f option. This forces Git to override all local changes, so be aware: this will cause any changes you made to be lost.
Collections in Hibernate
If you recall from Hibernate Basics, 0:00 we used JPA annotations on our entity classes. 0:02 Remember JPA stands for Java Persistence API, and 0:05 consists of a set of standards that providers such as Hibernate implement. 0:09 We have a couple entity classes in our application, the Gif class and 0:14 the Category class. 0:17 Let's add JPA annotations to those so 0:19 that Hibernate knows how to map its fields to database columns. 0:21 Let's do that now. 0:25 Now that we've configured our Spring app to pick up any JPA annotated 0:27 entities on boot, like we did right here, with the setPackagesToScan line, 0:32 now it's time to add those JPA annotations to our entities. 0:37 Let's start with the Category class. 0:41 Remember our entities classes are in the model package. 0:43 So we're going to start with the Category class. 0:47 We'll start by adding the entity annotation. 0:49 Next we'll annotate what will be the primary key of the category table, 0:54 and that is the ID field. 0:58 So I'll annotate this with the javax.persistence.Id annotation and 1:00 I'll specify that this is a GeneratedValue using 1:07 the strategy GenerationType.IDENTITY. 1:12 We'll use this IDENTITY generation type to tell H2 that it should automatically 1:16 insert IDs as unique to the table. 1:20 These will be sequentially assigned ids starting with one. 1:24 Now if you recall from Hibernate Basics, 1:29 if we include a field that has been annotated with this Id annotation, 1:31 then every other non-transient field will be marked as a column. 1:36 So therefore we'll get every field marked here as a column in the category table so 1:41 there's no need to include that column annotation on the other fields. 1:45 Now there is one exception to this and that is the Gif field, 1:51 this gifs list right here, and this is a collection. 1:55 Unless we plan on marking this field as transient, we'll need to indicate 1:59 a relationship between the Category entity and the Gif entity. 2:02 And this opens up a whole world within the world of ORM, 2:07 and in particular collection mapping. 2:10 Check the teacher's notes for resources to investigate more about this. 2:13 For now, I'd like you to know about two types of collection mapping, and these 2:17 line up with relationships that are very common among database relational data. 2:22 They are the one-to-many relationship and a many-to-one relationship. 2:27 In this entity, one Category object can be associated with many Gif objects. 2:33 So we'll annotate this list of Gifs with just that annotation, OneToMany. 2:39 As for the many-toone relationship, 2:47 we can use the Gif entity as an example for the flip side of this relationship. 2:49 So we have a one-to-many relationship between categories and GIFs. 2:54 So if we flip to Gifs, what we'll have is a many-to-one relationship here 2:58 since many Gif objects can be associated with one Category object. 3:05 So I'll use ManyToOne right here. 3:12 And while we are in this class, let's add the rest of all necessary JPA annotations. 3:16 So again, we better annotate the class with the Entity annotation, 3:21 as well as the primary key field with the Id annotation, as well as specifying that 3:26 it is a Generated value using that same strategy as we did in the Category class. 3:33 That is, the GenerationType.IDENTITY strategy. 3:39 Now, on this bytes field we are going to use the Lob annotation. 3:44 This allows us to store the GIF image file data into the database 3:49 using the database provider's implementation of a large object, 3:53 which is exactly what Lob stands for, large, there's the L, and object. 3:58 Now let's switch back to Category.java for 4:04 just one more change before we fire up the application. 4:06 If we were to run the application now, we'd find that Hibernate's hbm2ddl 4:10 tool would create a separate table to associate GIFs with categories. 4:15 I know this might be desirable. 4:19 For purposes of simplicity in this course, we instead might 4:21 want to include the category ID as a column in the GIF table. 4:26 This means that every GIF would be associated to a category by referencing 4:30 its category ID in the GIF table. 4:35 And to achieve this effect, we can tell Hibernate that each of these Gif objects 4:37 is a map to the category field of the associated object by including 4:42 a mappedBy element on this annotation here. 4:47 So we'll include a mappedBy element here and 4:51 say that it's mapped to the category entity. 4:54 Now, what this means is that it's the category field in the GIF entity 4:58 that will be used to map the category of each GIF. 5:03 And by default, this will use the category's ID field, 5:06 that is the field that's been marked with the Id annotation, and thereby creating 5:10 a column name CATEGORY_ID in the GIF table which we'll see in just a moment. 5:15 So, with that said, let's fire up this app and check out the schema that's created. 5:21 Now, just in case you've closed and reopened your IDE since the last video or 5:26 for whatever reason your database server isn't currently running, 5:30 let me run through that again quickly. 5:34 If yours is still running, you can skip this step. 5:36 Now for me, mine is still running. 5:38 I'm gonna kill my server. 5:40 Again, you don't have to do this if yours is still running. 5:41 To kill the server, you can hit Ctrl+C. 5:44 I'm gonna clear my console. 5:47 And now I'll run the database in server mode by using the Java command. 5:49 Remember we gotta stick that jar file on the classpath and 5:53 then the main class is located in org.h2.tools.Server. 5:58 And when you hit enter, that should open a new browser tab, and 6:04 here is that web console again. 6:08 And do make sure that your database URL is correct In this JDBC URL text box. 6:10 Go ahead and click Connect here. 6:19 And you can see once again we have no tables in our database. 6:23 They would be listed right here. 6:27 And that's about to change. 6:29 Let's go back to IntelliJ and run our bootRun task. 6:31 So I'm going to open the great old tool window here, and double-click on bootRun. 6:36 Now, as this is booting you should see some output 6:42 indicating that your application has compiled and 6:45 then eventually that it has opened successfully. 6:48 Now you should see this Spring logo here as your application starts to boot. 6:52 All this output tells me that the application compiled correctly. 6:59 And now here is Spring beginning to boot. 7:03 If you see errors after this, those are runtime 7:06 errors that you might have to go back and debug upon booting your application. 7:08 But it looks like my application started successfully, so let's go have a look. 7:13 What I'd like to do is switch back to the web console and see if that hbm2ddl 7:21 tool found my annotated entities and created database tables out of them. 7:26 So let me hit this refresh icon right here. 7:33 And there you see them, there's a category table and a GIF table. 7:37 If I expand the CATEGORY table here, I'll see one field for, I should 7:42 say one column for each of the fields that I included in the Category entity class. 7:47 If I expand the GIF table I should see the same. 7:53 And there is that CATEGORY_ID field that we talked about by using 7:57 the mappedBy element in the OneToMany annotation. 8:02 And if you look at the BYTES column here, 8:08 you'll see that it was created as a BLOB field. 8:10 Now this stands for Binary Large Object, and 8:14 it is there to hold the binary data of all of our GIF images. 8:17 So congratulations on getting your database server up and running with 8:22 the two tables created that you'll need to run Giflib integrated with Hibernate. 8:25 We now have our two entity classes decorated with JPA annotations, 8:33 which will be picked up by Spring because we use Spring's LocalSessionFactoryBean 8:37 to scan our model package. 8:42 This is one advantage of using Spring's scanning mechanism. 8:44 In plain old Hibernate, 8:48 we would have had to add an XML mapping element for each entity class. 8:49 Next we'll start writing the code that fires up this Hibernate engine and 8:54 finally test our application. 8:58
You need to sign up for Treehouse in order to download course files.Sign up