blob: 39b6d8d9ee2ac04147be1eb446aacc93fe3c3b3c [file] [log] [blame]
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/
/*
* Copyright (C) 2020-2022 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.jdbc;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityTransaction;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.pekko.japi.function.Function;
import org.apache.pekko.projection.jdbc.JdbcSession;
// #hibernate-session-imports
import org.hibernate.Session;
// #hibernate-session-imports
// #hibernate-session
public class HibernateJdbcSession implements JdbcSession {
public final EntityManager entityManager;
private final EntityTransaction transaction;
public HibernateJdbcSession(EntityManager entityManager) {
this.entityManager = entityManager;
this.transaction = this.entityManager.getTransaction();
this.transaction.begin();
}
@Override
public <Result> Result withConnection(Function<Connection, Result> func) {
Session hibernateSession = entityManager.unwrap(Session.class);
return hibernateSession.doReturningWork(
connection -> {
try {
return func.apply(connection);
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new SQLException(e);
}
});
}
@Override
public void commit() {
transaction.commit();
}
@Override
public void rollback() {
// propagates rollback call if transaction is active
if (transaction.isActive()) transaction.rollback();
}
@Override
public void close() {
this.entityManager.close();
}
}
// #hibernate-session