From c72d565bb58226b20625b2bce5f0019046bee649 Mon Sep 17 00:00:00 2001 From: "Sonsino, Ofir (os0695)" Date: Tue, 10 Jul 2018 14:20:54 +0300 Subject: Merge 1806 code of vid-common Change-Id: I75d52abed4a24dfe3827d79edc4a2938726aa87a Issue-ID: VID-208 Signed-off-by: Sonsino, Ofir (os0695) --- .../src/main/java/org/onap/vid/utils/DaoUtils.java | 53 ++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java (limited to 'vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java') diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java b/vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java new file mode 100644 index 00000000..c8a91626 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/utils/DaoUtils.java @@ -0,0 +1,53 @@ +package org.onap.vid.utils; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.portalsdk.core.FusionObject; + +import java.util.HashMap; +import java.util.function.Function; + +public class DaoUtils { + + //all credit for this wonderful method go to is9613 + public static T tryWithSessionAndTransaction(SessionFactory sessionFactory, Function update) { + // opens a session and transactions, executes the input query. + // gracefully close session and transaction once error occurres. + Session session = null; + Transaction tx = null; + try { + session = sessionFactory.openSession(); + tx = session.beginTransaction(); + + T res = update.apply(session); + + tx.commit(); + + return res; + } catch (RuntimeException e) { + try { + if (tx != null) { + tx.rollback(); + } + } catch (RuntimeException e2) { + // e2 is ingnored; we would like to know the + // original failure reason, not only the reason + // for rollback's failure + throw new GenericUncheckedException("Failed rolling back transaction", e); + } + throw new GenericUncheckedException("Rolled back transaction", e); + } finally { + if (session != null) { + session.close(); + } + } + } + + public static HashMap getPropsMap() { + HashMap props = new HashMap<>(); + props.put(FusionObject.Parameters.PARAM_USERID, 0); + return props; + } +} -- cgit 1.2.3-korg