休眠 returns "weird" 连接

Hibernate returns "weird" connection

我在一个带有 Hibernate 的项目中使用 JPA,我需要在纯 JDBC 级别上执行一些操作,所以我使用这种方法来获得与我的数据库的连接:

public class ConnectionUtil {
    public static EntityManagerFactory EMF = Persistence
        .createEntityManagerFactory("persistenceUnitName");

    public static Connection getConnection() throws SQLException {

        Connection connection = null;
        EntityManager em = null;
        try {
            em = EMF.createEntityManager();
            Session session = (Session)EMF.createEntityManager()
                    .getDelegate();
            SessionFactoryImplementor sfi = (SessionFactoryImplementor) session
                    .getSessionFactory();
            @SuppressWarnings("deprecation")
            ConnectionProvider cp = sfi.getConnectionProvider();
            connection = cp.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (em != null) {
                em.close();
            }
        }

        return connection;
    }
}

我使用这种方法将记录插入到我的数据库中:

public void saveOrUpdate(String sqlStatement, Connection connection,  Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {

            preparedStatement = connection.prepareStatement(sqlStatement);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            preparedStatement.execute();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

实现如下所示:

saveOrUpdate("INSERT INTO my_table(my_column) VALUES (?)", ConnectionUtil.getConnection(), "MyValue");

没什么特别的。除了.. 它不起作用。没有例外,没有。但是没有插入记录。选择按预期工作。它 returns 记录。然后我交换了连接。我以经典方式创建连接:

  Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","u","p");

通过了 c 而不是 ConnectionUtil.getConnection() 并且成功了。

然而,这种情况下的逻辑问题是:

如果我无法使用 getConnection 方法返回的连接插入记录,那么 Hibernate 如何在使用相同连接的情况下插入记录?

ConnectionProvider 不打算被应用程序使用,检查 documentation

The ConnectionProvider interface is not intended to be exposed to the application. Instead it is used internally by Hibernate to obtain connections.

因此,更好的选择是第二种方法,以经典方式获得连接。