From 2ddaaadcd96b852b9783c4c2fcba3b087ecfa36c Mon Sep 17 00:00:00 2001
From: Christopher Bohn <bohn@unl.edu>
Date: Sat, 29 Feb 2020 08:25:38 -0600
Subject: [PATCH] Prevented NullPointerException when closing a null session

Since the end-state of closeSession() is to have a null session, if
session is already null, there is nothing to do.
---
 .../cse/csce361/hibernate/FruitPopulator.java | 20 ++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/src/main/java/edu/unl/cse/csce361/hibernate/FruitPopulator.java b/src/main/java/edu/unl/cse/csce361/hibernate/FruitPopulator.java
index 8dddbc2..26f9ef9 100644
--- a/src/main/java/edu/unl/cse/csce361/hibernate/FruitPopulator.java
+++ b/src/main/java/edu/unl/cse/csce361/hibernate/FruitPopulator.java
@@ -28,14 +28,16 @@ public class FruitPopulator {
     }
 
     public static void closeSession(Session session) {
-        try {
-            session.close();
-        } catch (HibernateException hibernateException) {
-            System.err.println("Failed to close session due to Hibernate problem.  " + hibernateException);
-            System.err.println("Abandoning possibly-open session.");
-        } finally {
-            //noinspection UnusedAssignment
-            session = null;
+        if (session != null) {
+            try {
+                session.close();
+            } catch (HibernateException hibernateException) {
+                System.err.println("Failed to close session due to Hibernate problem.  " + hibernateException);
+                System.err.println("Abandoning possibly-open session.");
+            } finally {
+                //noinspection UnusedAssignment
+                session = null;
+            }
         }
     }
 
@@ -70,7 +72,7 @@ public class FruitPopulator {
         FruitSalad fruitSalad = session.load(FruitSalad.class, 4);  // This is INCREDIBLY fragile
         session.getTransaction().commit();
         System.out.print(fruitSalad + " contains ");
-        for(Fruit fruit: fruitSalad.getFruits()) {
+        for (Fruit fruit : fruitSalad.getFruits()) {
             System.out.print(fruit + " and ");
         }
         System.out.println("that is all.");
-- 
GitLab