Hibernate4 configuration without xml files - sessionFactory is null

I have a web project working with Spring3 and Hibernate4, and now I want to test the DAO without using xml files. To do this, I created a class that creates a LocalSessionFactoryBean with the data contained in the application xml file and a simple test class.

However, the sessionFactory returned by localSessionFactoryBean.getObject () is NULL. I looked at some examples like this and they have the same problem when I modify them to work without Spring. Do you have any ideas?

This is the code that prepares sessionFactory:

@Configuration
@Transactional
@EnableTransactionManagement
@ComponentScan({ "com.company" })
public class HibernateInitializator {

    public SessionFactory getSessionFactory() {

        Properties hibernateProperties = getHibernateProperties();
        DataSource dataSource = getDatasourceConfiguration();
        LocalSessionFactoryBean localSessionFactoryBean = generateSessionFactoryBean(new String[] { "com.company" },
            dataSource, hibernateProperties);
        SessionFactory sessionFactory = localSessionFactoryBean.getObject();

        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);

        return sessionFactory;
    }

    private DataSource getDatasourceConfiguration() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/dbName");
        dataSource.setUsername("username");
        dataSource.setPassword("password");

        return dataSource;
    }

    private static LocalSessionFactoryBean generateSessionFactoryBean(String[] basePackage, DataSource dataSource,
        Properties hibernateProperties) {

        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(dataSource);
        localSessionFactoryBean.setPackagesToScan(basePackage);
        localSessionFactoryBean.setHibernateProperties(hibernateProperties);

        return localSessionFactoryBean;
    }

    private static Properties getHibernateProperties() {

        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
        hibernateProperties.put("hibernate.show_sql", false);
        hibernateProperties.put("hibernate.generate_statistics", false);
        hibernateProperties.put("hibernate.hbm2ddl.auto", "update");
        hibernateProperties.put("hibernate.use_sql_comments", false);

        return hibernateProperties;
    }
}

And this is a simple test class that uses it:

public class GenericDAOHibernateTest {

    private GenericDAOHibernate dao;

    @BeforeTest
    private void testInitialization() {

        dao = new GenericDAO();
        HibernateInitializator initializator = new HibernateInitializator();
        SessionFactory sessionFactory = initializator.getSessionFactory();
        dao.setSessionFactory(sessionFactory);
    }

    @Test(description = "Checks that returns the user list ")
    public void shouldReturnsUserList() throws SQLException, Exception {

        List<Object[]> openResultSetList = dao.doSomeOperation();
        ...
    }
}
+4
source share
3

localSessionFactoryBean.afterPropertiesSet();

, LocalSessionFactoryInstance.

private static LocalSessionFactoryBean generateSessionFactoryBean(String[] basePackage, DataSource dataSource,
        Properties hibernateProperties) {
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(dataSource);
        localSessionFactoryBean.setPackagesToScan(basePackage);
        localSessionFactoryBean.setHibernateProperties(hibernateProperties);
        // Added the below line
        localSessionFactoryBean.afterPropertiesSet();
        return localSessionFactoryBean;
    }

.

,

public void afterPropertiesSet() IOException

BeanFactory , bean ( BeanFactoryAware ApplicationContextAware). bean , bean .

, , .

+9

, XML , , @Octopus, , . ... -, .

xml /src/test/resources, c3p0 one hardcoding , , .

xml:

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" ...>

    <!-- Spring DataSource -->
    <bean id="testDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/testDatabase" />
        <property name="username" value="testUsername" />
        <property name="password" value="testPassword" />
    </bean>

    <!-- Hibernate 4 SessionFactory -->
    <bean id="testSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="testDataSource">
        <property name="packagesToScan" value="com.company" />
        <property name="hibernateProperties">
            <props>
                <!-- Hibernate basic configuration -->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.generate_statistics">false</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.use_sql_comments">false</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="dataSource" ref="testDataSource" />
        <property name="sessionFactory" ref="testSessionFactory" />
    </bean>

    <context:annotation-config />
    <tx:annotation-driven />

    <!-- Initialization of DAOs -->
    <bean id="userDao" name="userDao" class="com.company.dao.UserDAOHibernate" autowire="byName"/>
    ... 
</beans>

JUnit, TestNG, AbstractTestNGSpringContextTests. JUnit 4.4 , , AssumptionViolatedException, spring -test 2.5.

:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/test/resources/application-config-tests.xml" })
public class SimpleUserDAOTest {

    @Autowired
    private UserDAO dao;

    @Autowired
    private SessionFactory sessionFactory;

    @Before
    public void setUp() throws Exception {
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(sessionFactory.openSession()));
    }

    @After
    public void tearDown() throws Exception {
        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
        SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }

    @Test
    public void shouldReturnActiveUsers() {
        List<User> userList = dao.getActiveUsers();
        ...
    }
}

,

+3

Spring 3+ Hibernate 4, , Spring , .

, , Autowire SessionFactory DAO Spring:)

@Configuration
@Import(HibernateConfig.class)
@EnableWebMvc
@ComponentScan(basePackages = "com.mypackages")
public class WebConfig extends WebMvcConfigurationSupport {

@Override
protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.parameterName("mediaType").ignoreAcceptHeader(true)defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", MediaType.APPLICATION_JSON);
}

@Bean(name = "validator")
public Validator validator() {
    return new LocalValidatorFactoryBean();
}
} 

a HibernateConfig, :

@Configuration
@EnableTransactionManagement
@EnableAspectJAutoProxy
@PropertySource({"classpath:app.properties"})
@ComponentScan(basePackages = "com.mypackages")
public class HibernateConfig {

@Value(Constants.HIBERNATE_DIALECT)
private String hibernateDialect;

@Autowired
private DataSource dataSource;

@Bean(name = "appProperty")
public static PropertySourcesPlaceholderConfigurer appProperty() {
    return new PropertySourcesPlaceholderConfigurer();
}

@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory() throws Exception {

    Properties properties = new Properties();
    properties.put(Constants.HIBERNATE_DIALECT_PROPERTY,
            hibernateDialect);
    properties.put(Constants.HIBERNATE_SHOW_SQL_PROPERTY,
            "false");
    properties
            .put(Constants.HIBERNATE_CURRENT_SESSION_CONTEXT_CLASS_PROPERTY,
                    "thread");
    properties
    .put("dynamic-update","true");
    LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
    factory.setPackagesToScan(new String[] { Constants.DOMAIN_MODEL_PACKAGE });
    factory.setDataSource(dataSource);
    factory.setHibernateProperties(properties);
    factory.afterPropertiesSet();
    return factory.getObject();
}

@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager() throws Exception {
    return new HibernateTransactionManager(getSessionFactory());
}
}

a JndiConfig, :

@Configuration
public class JndiConfig {

@Value(Constants.DRIVER_CLASS)
private String driverClassName;
@Value(Constants.DATABASE_URL)
private String databaseURL;
@Value(Constants.USER_NAME)
private String username;
@Value(Constants.PASSWORD)
private String password;
@Value(Constants.MAX_ACTIVE)
private int maxActive;
@Value(Constants.MAX_IDLE)
private int maxIdle;
@Value(Constants.MAX_WAIT)
private long maxWait;
@Value(Constants.MIN_IDLE)
private int minIdle;
@Value(Constants.INITIAL_SIZE)
private int initialSize;
@Value(Constants.TIME_BETWEEN_EVICTION)
private long timeBetweenEvictionRunsMillis;

@Bean(name = "dataSource")
public DataSource dataSource() throws Exception {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(databaseURL);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setTestOnBorrow(true);
    dataSource.setTestWhileIdle(true);
    dataSource.setValidationQuery("SELECT 1");
    dataSource.setMaxActive(maxActive);
    dataSource.setMaxIdle(maxIdle);
    dataSource.setMaxWait(maxWait);
    dataSource.setMinIdle(minIdle);
    dataSource
            .setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

    return dataSource;
}
}
0

Source: https://habr.com/ru/post/1542151/


All Articles