Hibernate Unchecked Assignment Java

  • 0:00

    Once again way to go on verifying that your Contact objects are being persisted

  • 0:05

    into your database.

  • 0:06

    With simple console output, we were able to spy on the sequel that

  • 0:10

    Hibernate was generating and firing off to H2 for final processing.

  • 0:15

    This kind of monitoring of a Hibernate queries is useful in many scenarios.

  • 0:19

    Especially when fine-tuning the performance of Hibernate and

  • 0:23

    minimizing both the number of times your application has to hit the DB

  • 0:27

    as well as the amount of time each query is taking.

  • 0:31

    In our case though, it's only a stepping stone to using our data and

  • 0:35

    displaying it more naturally in the application.

  • 0:38

    What we'll look at now is how to use Hibernate to fetch a list of

  • 0:41

    all the objects of a certain entity class that have been persisted to the database.

  • 0:46

    Let's have a look at the most basic way of doing that with what is called Hibernate

  • 0:50

    criteria.

  • 0:51

    Here in application.java, I'd like to do some refactoring first.

  • 0:58

    Since we currently have code saving a Contact object, and we're about to

  • 1:01

    write code to retrieve contact objects, let's split those into separate methods.

  • 1:06

    Let's create a method named save and have it persist as supplied contact.

  • 1:11

    I'll get the method signature in here now, private static void save.

  • 1:16

    And I want to save a Contact object, I'll name it contact.

  • 1:20

    And into here,

  • 1:21

    I'm gonna drop all that code that we previously put into the main method.

  • 1:26

    Great. Then, back up in main, we can simply call

  • 1:29

    the save method with the Contact object we created using the builder, just like this.

  • 1:37

    Save contact.

  • 1:39

    Next, let's create a method that will retrieve or

  • 1:42

    fetch all of our Contact objects from the database.

  • 1:45

    Let's call it fetchAllContacts.

  • 1:48

    So, private static will return a list, that's a java.util list,

  • 1:55

    of Contact objects and we'll call it fetchAllContacts.

  • 2:01

    Because we're interacting with a database using Hibernate this will involve

  • 2:05

    opening a session, doing some stuff, then closing the session.

  • 2:08

    So let's get that session open and close in there right away.

  • 2:13

    So we'll first open a session, we'll do some other things but

  • 2:17

    finally we'll close the session.

  • 2:21

    So again, to open the session, it's the same code as before,

  • 2:24

    session = sessionFactory.openSession.

  • 2:29

    And to close the session, we simply call the close method on that S~ession object.

  • 2:34

    Cool.

  • 2:36

    Now between these two lines of code, while the session is open,

  • 2:39

    that's where our magical code will come into play.

  • 2:42

    To retrieve all contacts as a list of contact objects

  • 2:45

    we'll use what's called a Hibernate Criteria object.

  • 2:48

    In Hibernate, a Criteria object can be used to filter results according to one or

  • 2:52

    more restrictions.

  • 2:54

    In its most basic form,

  • 2:56

    a criteria can be used to produce a list of persisted entity objects.

  • 3:00

    Here's how it looks, so first, we're going to create the Criteria object.

  • 3:07

    I'll declare a criteria variable that comes from org.Hibernate,

  • 3:10

    I'll call it criteria and into it I'll store a call to session.createCriteria.

  • 3:17

    And here is where we put a reference to the contact class,

  • 3:22

    that's Contact.class.

  • 3:26

    Whereas we could add all sorts of restrictions to the Criteria object here

  • 3:29

    such as restricting results to contacts whose first name is Fiona or

  • 3:34

    whose email contains teentreehouse.com.

  • 3:37

    We can simply leave the Criteria object as is, and call its list method.

  • 3:42

    So let's create a list of Contact objects.

  • 3:46

    That will be a list of Contact objects, I'll call it contacts.

  • 3:51

    And store into it the results of calling that list method.

  • 3:54

    Criteria.list.

  • 3:59

    Let me add a comment here that says exactly what I'm doing.

  • 4:02

    Get a list of Contact objects

  • 4:07

    according to the Criteria object that we just created.

  • 4:12

    Now, after we close the session, we'll need to return that list of contacts,

  • 4:16

    return contacts.

  • 4:18

    Now, you might notice that you get some faint highlighting over critera.list.

  • 4:24

    What this is is a compiler warning telling us that we have an unchecked assignment.

  • 4:30

    The Criteria objects list method returns an unparamaterized list and

  • 4:34

    we're assigning it to a paramaterized list that is a list of Contact objects.

  • 4:39

    If you recall from our annotations course, we can suppress compiler warnings.

  • 4:43

    Because we don't have access to alter the hibernate source

  • 4:46

    code to resolve this assignment,

  • 4:48

    this is one of those few scenarios when it is acceptable to suppress the warning.

  • 4:53

    So let's do that with a SuppressWarnings annotation.

  • 4:58

    SuppressWarnings and

  • 5:00

    we will suppress the unchecked assignment warning using the string unchecked.

  • 5:06

    Excellent, the warning is now suppressed.

  • 5:10

    Now, to put this to work.

  • 5:12

    Let's go back up to the main method and

  • 5:14

    display a list of contacts using its two-string method.

  • 5:18

    So, here I'm going to display a list of contacts by using a for loop.

  • 5:26

    So I'm going to iterate over all contacts

  • 5:30

    that come back from the fetchAllContacts method.

  • 5:33

    And in here, I'm simply going to use a System.out.println of c.

  • 5:40

    Now, let's run the application again, to see our Contact objects displayed.

  • 5:44

    So I'll right click here and choose Run.

  • 5:48

    And you'll see a bunch of Hibernate output until finally we get

  • 5:51

    to our applications output.

  • 5:54

    And here are the results of our two-string method which show that we did

  • 5:58

    indeed successfully persist that Contact object using our method.

  • 6:04

    And successfully retrieved that list of contacts,

  • 6:08

    even though there is only one, using Hibernate, excellent.

  • 6:12

    Now you may wonder that after running this application a few times,

  • 6:17

    why is it that you always get just one contact in your database?

  • 6:22

    Each time I run it I still get just one contact in my database.

  • 6:27

    You might be asking, doesn't the data continue to exist after exiting and

  • 6:31

    re-running the application?

  • 6:33

    After I run it a second time shouldn't there be two contacts in there?

  • 6:37

    And a third time, shouldn't there be three contacts in there?

  • 6:41

    The answer to those questions is, well, no.

  • 6:44

    And that is because we told the HBM to DDL tool to create

  • 6:48

    our database schema on startup.

  • 6:50

    If we go back to that configuration file, we can remind ourselves that we set

  • 6:55

    the HBM to DDL.autoproperty to create.

  • 6:59

    That means that any previous data will be wiped out on application startup.

  • 7:04

    And we can change that property value to update so that only database schema

  • 7:11

    changes will be made instead of blowing away our whole schema and recreating.

  • 7:16

    Let me update the comment here.

  • 7:18

    Update the database schema on startup.

  • 7:20

    So now, when we rerun the application, if Hibernate detects that there have been

  • 7:25

    changes in the schema as indicated by our JPA annotations.

  • 7:30

    The table or tables will be altered by the HBM to DDL

  • 7:35

    tool without changing the data that exists in those tables.

  • 7:41

    So, after making that change, let me stop the application.

  • 7:46

    I will delete all the output in my terminal here and I will rerun.

  • 7:50

    Let's see what kind of data we get now.

  • 7:54

    There you have it, we have two contacts here.

  • 7:57

    Of course, because our application code only specifies information for

  • 8:01

    one contact, we'll continue getting the same info for each contact, but

  • 8:05

    with one exception, the id here.

  • 8:08

    In the second contact it's 2, in the first contact it's 1.

  • 8:13

    Remember the id field is automatically generated, so

  • 8:17

    that each contact has a unique id in the database.

  • 8:21

    As a fun side note, if we switch back to application.java,

  • 8:25

    we can use some of the new features offered by Java 8 to condense our code.

  • 8:29

    Specifically, this code right here.

  • 8:32

    This for each loop can be simplified by using what's called a stream, and

  • 8:36

    on that stream we can call a method named, for each.

  • 8:39

    Passing to it, a reference to the system.out classes static printlin method.

  • 8:43

    Let me show you how that looks.

  • 8:45

    We'll call the fetchAllContacts method and on that list we will create a Java stream.

  • 8:52

    And here is where we can call this method named forEach, passing a method reference,

  • 8:57

    which is new in Java 8, to the println.

  • 9:00

    The system that out-classes static println method.

  • 9:05

    And, after running this, you should see that we get the same output.

  • 9:09

    Let me stop our previous run of the application, trash our output, and

  • 9:14

    re-run it to see if we get the same output.

  • 9:17

    Excellent, we do get the same output.

  • 9:19

    And now we have three contacts, pretty sweet stuff.

  • 9:23

    Check out the Teacher's Notes for some more features introduced in Java 8.

  • Wow; I think I figured out the answer to my own question. I'm just not sure it's worth it! :)

    The problem is the cast isn't checked. So, you have to check it yourself. You can't just check a parameterized type with instanceof, because the parameterized type information is unavailable at runtime, having been erased at compile time.

    But, you can perform a check on each and every item in the hash, with instanceof, and in doing so, you can construct a new hash that is type-safe. And you won't provoke any warnings.

    Thanks to mmyers and Esko Luontola, I've parameterized the code I originally wrote here, so it can be wrapped up in a utility class somewhere and used for any parameterized HashMap. If you want to understand it better and aren't very familiar with generics, I encourage viewing the edit history of this answer.

    That's a lot of work, possibly for very little reward... I'm not sure if I'll use it or not. I'd appreciate any comments as to whether people think it's worth it or not. Also, I'd appreciate improvement suggestions: is there something better I can do besides throw AssertionErrors? Is there something better I could throw? Should I make it a checked Exception?

    Categories: 1

    0 Replies to “Hibernate Unchecked Assignment Java”

    Leave a comment

    L'indirizzo email non verrĂ  pubblicato. I campi obbligatori sono contrassegnati *