Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Updating and Deleting Entities9:53 with Chris Ramacciotti
Moving on through the CRUD operations, you have yet to cover updating and deleting. In this lesson, you again use the Hibernate `Session` to perform these operations.
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/contactmgr-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.
In the context of the basic CRUD operations in our application, 0:00 we're only half-way there. 0:04 We've discussed creating with a hibernate session save and 0:06 reading with a hibernate criteria. 0:10 Let's now turn to updating and deleting so that you have a more solid foundation for 0:12 further research and experimentation with Hibernate. 0:17 In both the update and delete scenarios we'll need a persistent object. 0:21 What this means is that we'll have to have already fetched the object from 0:26 the data base so in each of these cases we'll first find a contact by ID. 0:28 Let me show you how that's done in hibernate. 0:33 To keep our application class tidy I'll make another method for 0:35 getting a contact with a certain ID and I'll include comments for 0:38 what we're gonna do in this method. 0:41 We'll do this right below the main method. 0:43 We'll call it private static, it's gonna return a contact object and 0:46 I'll say find contact by ID using a given int ID. 0:51 So the first thing we'll do is open a session, this should look familiar. 0:58 We'll retrieve the persistent object. 1:01 Or null if it's not found. 1:07 We'll close the session. 1:11 And finally will return the contact object. 1:13 Most of this we've already done before so I'll fill in those pieces now. 1:18 To open the session, as you recall, we'll declare a session and 1:21 we'll use the sessionFactory to open a session. 1:25 This is the line that we'll come back to in just a moment. 1:29 To close the session that's a simple call to session.close. 1:32 And finally returning that object return contact. 1:36 Speaking of that contact object, hibernate provides a simple way to retrieve 1:41 a persistent object using its identifier and that is the session's get method. 1:44 Here's how it looks. 1:49 So into this contact variable we will assign session.get. 1:51 We'll specify the name of the entity class and we will give it 1:56 the integer identifier associated with the contact object that we're looking for. 2:01 And that's all we need for the findContactById method. 2:06 Now let's write a method that will take this contact object and 2:09 persist any changes to the database. 2:13 Let's create the method stub and comments for what we need to accomplish. 2:15 I'll do that below the current method, private static void, 2:19 we'll call it update and we wanna update the specified contact object. 2:23 So again, we will open a session here we'll begin a transaction, 2:27 since there are changes to be written to the database, 2:32 we'll use the session to update the contact. 2:36 We'll commit the transaction and finally we'll close the session. 2:41 Now, all of this will likely look fairly intuitive and 2:48 in line with the code that we've used to save an entity. 2:51 In fact, the only difference is gonna be that instead of calling the save method, 2:55 we'll be calling sessions update method which you 2:58 probably could've guessed with your IDE code suggestions. 3:01 So let's get this thing done. 3:04 First we will open a session. 3:06 Session = sessionFactory.opensession. 3:09 We'll begin the transaction by using session.beginTransaction. 3:15 Here's the one line that's different from saving a new entity, 3:20 we'll say session.update the contact. 3:23 Then we will commit the transaction. 3:28 Session.getTransaction, that gets the open transaction that commit and 3:31 finally we will close the session. 3:37 Session.close. 3:40 Now with that done let's pull it all together in the main method. 3:42 So let me scroll back up here to the main method. 3:45 What I'd like to do is update the contact that we saved 3:49 at the beginning of this method, that is this contact object here. 3:52 To do this we'll need to have its ID. 3:57 But because this was generated by the database we don't currently have 4:00 access to this integer ID in our source code. 4:04 But hibernate has a solution for that. 4:08 Whenever an entity is saved with a sessions save method, 4:11 that save method returns the assigned identifier, 4:14 whether its generated by application code or by the database, as is the case for us. 4:17 Let's scroll down to the save method and update it to return the int id. 4:22 To do that right here we will say, int id = session.save. 4:29 Now the save method returns a serializable object so 4:35 we'll need to cast that return value to an int. 4:39 Wonderful, next we'll return the integer ID and add the return type. 4:43 So at the bottom here let's return the I, and 4:48 instead of making this a void method let's switch that to an int. 4:52 So we now have access to the generated ID up in our main method. 4:56 So I will scroll back up and alter my code there. 4:59 So before the save I'll add an int ID = save contact. 5:03 Let's create a log of outputs so that we can observe the progress of 5:09 all of our steps and verify that our update indeed works. 5:12 So this first display of our contacts is gonna be displaying a list of contacts 5:16 before the update. 5:20 And the next thing that we're going to do is get the persistent contact. 5:24 We'll update the contact. 5:30 We'll persist the changes and 5:32 then we'll display a list of contacts after the update. 5:39 Now let's back fill a couple lines of code for 5:45 retrieving the contact, altering it, then persisting those changes. 5:48 So for getting the persisted contact we will say contact, 5:52 I'll call it C in this case, equals findContactById, and here's the integer 5:57 Id that will have been generated when we persisted this initial contact. 6:03 So we'll hit the database again and grab the result as a contact object. 6:08 Then we can alter the contact just as we would any 6:14 other Java object by using a setter. 6:17 I'll alter the first name. 6:19 So under Update the contact, I'll say c.setFirstname and 6:21 I'll set the first name to Beatrix. 6:25 And to persist those changes we'll call the update method that we wrote 6:30 just a bit ago, update(c). 6:33 Now let's give ourselves a couple lines of output so 6:38 that we can monitor our progress along the way. 6:41 So right here I'll do a System.out.print f and I will say that this, 6:44 give myself a couple new lines, this is before the update. 6:51 Want those to stand out so I'll surround that update by a couple new line 6:57 characters, now let's give ourselves a couple lines of out put before and 7:01 after the update so we can monitor those changes as well. 7:05 I'll copy that before and after this 7:08 persist so this will be updating. 7:14 And then we'll display a message that says update complete. 7:21 And finally, let's display our list of contacts after the update. 7:29 I'm going to copy these two lines of code, 7:33 since we'll be doing essentially the same thing. 7:35 We'll paste it down here and I will change this to after 7:38 and we want to do the same thing for this second line of code which will again fetch 7:43 all contacts, create a stream out of it and on each one of those contact 7:48 objects we will pass that contact object to the system.out.println method. 7:53 And that's all there is to it. 7:59 Let's run our application to verify that everything is working. 8:00 Right click and choose run. 8:04 And if you look closely you will see that our first run through the output here 8:07 has our last contact, that is the one with the ID of four as a first name of Chris. 8:14 And then we have our update in which this hibernate query is run, 8:20 that is sent to the database. 8:25 Upon completion, we have our update complete, 8:27 and here's our list after the update. 8:29 Let's see if it worked. 8:31 Down at the bottom we have our contact with the ID of four, 8:33 whose last name has now been successfully persisted to the database. 8:35 As Beatrix, first name rather. 8:40 So as a recap of what we just did, we retrieved a persisted object that we 8:44 wanted by knowing it's ID and using the session's get method. 8:48 Then we altered the POJO using a basic setter. 8:52 Finally we called the session's update method to persist those changes. 8:55 And just like that our changes were persisted to the database. 8:59 Pretty cool stuff! 9:03 You might be wondering at this point why I haven't finished what I promised at 9:05 the beginning of this video. 9:09 How do you delete a persisted object? 9:11 I haven't forgotten though. 9:14 What I'd rather do is have you take a look at what you've learned from this course 9:16 and extend it to this one additional operation. 9:20 The delete operation. 9:23 You can try some things using your IDE's code suggestion tool or 9:25 you can hit up the online hibernate docs that I've linked to in the teachers notes. 9:29 Either way, be sure to give yourself plenty of output to verify successful 9:34 functionality. 9:38 Though you'll get the most out of accomplishing this yourself, 9:40 I've made my solution available on GitHub. 9:43 If you want to see it, Go to the online repo or 9:46 check out the revision named final. 9:49 Now have at it. 9:51
You need to sign up for Treehouse in order to download course files.Sign up