Saving Data with Hibernate6:23 with Chris Ramacciotti
This lesson demonstrates the use of a Hibernate `SessionFactory` to save a new entity to the database.
Java Transaction API Dependency
Though I included the JTA library in the Gradle build file as a compile-time dependency, you could instead list it as a runtime dependency, since no source code references the library:
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 firstname.lastname@example.org: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.
[MUSIC] 0:00 We're finally ready to see Hibernate in action by creating a contact object and 0:04 saving it to the database using a Hibernate session 0:09 that will come from the session factory we've created. 0:12 Let's check it out! 0:15 I'm in application.java. 0:16 And so that we can continue working on our hibernate features, 0:19 I'm going to uncomment the session factory static field. 0:22 Great. 0:27 Let's head down to the main method. 0:28 Now, we've created this contact object using this 0:30 findContact builder that we coded in the previous video. 0:33 It's time to persist this contact. 0:36 That is, it's time to save the contact to our database. 0:39 I'm going to take out this display of our contact object and 0:43 drop in some comments of what we need to do in order to persist our contact. 0:47 So the first thing we're going to do is open a session. 0:52 Then we will begin a transaction. 0:56 Third, we'll use this session to save the contact object. 1:02 Then we'll commit the transaction, and finally, we'll close the session. 1:08 We'll need just one statement for each comment, so this should be fairly quick. 1:17 First, to open a session, we simply use the SessionFactory we spent so 1:21 much time discussing while coding, and we call its open session method like this. 1:26 We'll declare the session variable, I'll call it session. 1:31 And using that SessionFactory static field, we'll call this openSession method. 1:35 Great. 1:40 The next thing we need to do is begin a transaction. 1:41 Now remember, a transaction is a thing that we use to contain 1:44 several queries into a single operation. 1:47 So let's say that if one query fails, we abort the whole transaction by 1:50 undoing all the previous queries within the transaction. 1:53 This would be called rolling back the transaction. 1:56 In hibernate, to begin a transaction, it's pretty straightforward. 1:59 sesson.beginTransaction. 2:03 While we're on the topic of transactions, in order to support hibernate 2:06 transactions, we'll need to add one more dependency to our gradle build file. 2:10 So I'll go ahead and open that now. 2:14 This new dependency is the JTA library, or Java Transaction API, and 2:17 here is how it looks in the gradle build file. 2:22 javax.transaction is the group ID. 2:25 jta is the artifact ID. 2:29 And version 1.1 is the one we're currently using. 2:32 Great, I'll save that. 2:35 And in my Gradle Tool Window, I will refresh my Dependencies. 2:37 Excellent, done with this build file so I'll close it. 2:44 Now back in the Application class, here's the one line of 2:48 code that will save us a bunch of time in interacting with our database. 2:51 It's the one that actually persists object to the database. 2:55 It is the save method, session.save, and 2:59 we simply pass it the object that we would like it to persist. 3:02 Now this object will have had to be annotated with those JPA annotations, 3:07 which we have done. 3:11 Next we will commit the transaction, which finalizes the transaction in the database. 3:13 To do that, we do session.getTransaction().commit();. 3:18 And finally, we'll close the hibernate session, session.close();. 3:26 And we're done. 3:33 Now because we're only inserting data into the database and 3:35 not selecting data from the database for 3:39 display, let's do something that let's us know our session save is actually working. 3:41 Let's hop over to the hibernate configuration file. 3:46 And use a property that tells hibernate to display its queries as they're executed. 3:50 Let me create a comment for this, And 3:54 in this property we will tell hibernate to show the queries prepared by Hibernate. 4:01 Now the property name, Is show_sql, 4:11 and we are going to set that value to true, pretty straightforward. 4:16 We want hibernate to show SQL queries, so we set the show_sql property to true. 4:23 Now, we can run the application and 4:30 what we should see are the queries performed by hibernate. 4:32 So let's go ahead and right click on application and 4:35 choose run and let's see what is displayed in the terminal. 4:38 You're gonna get a bunch of output here but in that output you should see 4:42 a create table statement is executed by Hibernate. 4:47 This will create a contact table. 4:52 Now this is generated by that hbm2ddl tool right here since we set this property, 4:54 hbm2ddl.auto we set that value to create. 5:00 Our database schema will be created by this tool based on those JPA annotations. 5:05 Then, a little further down in the output you should see this hibernate 5:11 insert statement, 5:16 which is where our contact object is actually persisted to the database. 5:17 Success! 5:22 Now, you might be wondering why you see question marks here instead of the actual 5:23 values used to create the object. 5:28 This is because hibernate uses what are called, prepared statements. 5:30 These are also referred to as parametrized statements, like statement templates that 5:34 the database, in our case H2, can optimize and keep on hand for repeated use. 5:39 Then, hibernate passes the parameter of values to stick into those question 5:45 mark placeholders. 5:49 Prepared statements help databases execute similar queries with different values 5:51 extremely efficiently. 5:55 Prepared statements aren't a feature of hibernate but 5:56 rather of a database system, but as you can see hibernate fully supports them. 5:59 Hey, nice work. 6:04 You've now bridged the gap between your application and a database and 6:06 you built that bridge with hibernate. 6:09 These results are promising but may not be completely convincing. 6:11 Let's break here so you can answer a couple questions. 6:16 And then, we'll explore some more features that Hibernate has to offer. 6:18
You need to sign up for Treehouse in order to download course files.Sign up