Java tutorial
/* * Copyright 2010-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.reusables.dbunit.handler; import org.reusables.test.SpringTestUtils; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.jdbc.Work; import org.springframework.test.context.TestContext; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** * Handler for a JDBC task using a Hibernate {@link SessionFactory} bean from a Spring test context. * * @author marcel */ public class HibernateSessionFactoryOperationHandler extends AbstractOperationHandler { /** * @param testContext The Spring test context containing the application context. */ public HibernateSessionFactoryOperationHandler(final TestContext testContext) { super(testContext); } /** * @param task The task to handle. * @return False if the {@link SessionFactory} bean was not present. */ @Override public boolean handleOperation(final JdbcTask task) { if (!isClassLoaded()) { return false; } final SessionFactory sf = getSessionFactory(); if (sf != null) { getSession(sf).doWork(new Work() { @Override public void execute(final Connection connection) throws SQLException { task.execute(connection); } }); return true; } return false; } /** * @param sessionFactory The session factory to use. * @return The session to use to handle the operation. * @since 1.2.0 */ protected Session getSession(final SessionFactory sessionFactory) { // The return value differs between Hibernate 3.x and 4.x; for cross-compilation purposes, // we have to use reflection here as long as we keep supporting Hibernate 3.x. final Method method = ClassUtils.getMethod(sessionFactory.getClass(), "getCurrentSession"); return (Session) ReflectionUtils.invokeMethod(method, sessionFactory); } /** * @return The {@link SessionFactory} to use. */ protected SessionFactory getSessionFactory() { return SpringTestUtils.findBeanByType(getTestContext().getApplicationContext(), SessionFactory.class); } /** * @return True if class {@link org.hibernate.SessionFactory} is loaded. * @since 1.2.1 */ protected boolean isClassLoaded() { // We have this class available, but the using project might not have it. return ClassUtils.isPresent("org.hibernate.SessionFactory", getClass().getClassLoader()); } }