在运行时更晚的时候更改SessionFactory数据源jdbcurl

时间:2012-09-27 01:41:11

标签: spring hibernate hsqldb

我正在为没有网络连接的环境编写桌面java应用程序。我正在尝试在加密的进程内hsqldb中安全地存储应用程序数据,并使用未加密的用户信息hsqldb。 Hsqldb要求在创建连接时在jdbcurl中设置crypto_key。我的应用程序使用hibernate来执行持久性,使用Spring来执行配置和注入。

我目前的方案是在未加密的用户表中存储用户名,密码哈希,salt和加密数据库的crypto_key。使用用户密码作为密钥,crypto_key受非对称加密保护。因此,应用程序不知道应用程序数据的crypto_key是什么,直到它运行足够长的时间来加载gui,并对用户进行身份验证。

这是我当前的applicationContext.xml。 Spring使用它来让Hibernate继续运行。

  <?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

<context:component-scan base-package="com.company.domain" />
<context:component-scan base-package="com.company.service" />

<tx:annotation-driven />

<bean id="userDataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" 
        value="jdbc:hsqldb:./ReviewDatabase/users" />
    <property name="username" value="reviewer" />
    <property name="password" value="$kelatonKey" />
</bean>


<bean id="mainDataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" 
        value="jdbc:hsqldb:./ReviewDatabase/data" /> <!-- TODO: ;crypt_key=;crypt_type=AES -->
    <property name="username" value="reviewer" />
    <property name="password" value="$kelatonKey" />
</bean>

<bean id="userSessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="userDataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.company.domain.AppUser</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

<bean id="mainSessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="mainDataSource" />
    <property name="annotatedClasses">
        <list>
<!--                <value>com.companu.domain.Person</value> -->
<!--                <value>com.company.domain.Thing</value> -->
<!--                <value>com.company.domain.Thing1</value> -->
<!--                <value>com.company.domain.Thing2</value> -->
<!--                <value>com.company.domain.Review</value> -->
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <pro key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>


<bean id="mainTransactionManager" 
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="mainSessionFactory" />
</bean>

<bean id="userTransactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="userSessionFactory" /> 
</bean>
</beans>

这是一个我想要注入SessionFactory的类的例子

@Repository("ReviewDao")
public class HibernateReviewDao implements ReviewDao{

private SessionFactory mainSessionFactory;

@Autowired
public void setMainSessionFactory(
        SessionFactory mainSessionFactory){
    this.mainSessionFactory = mainSessionFactory;
}

@Override
@Transactional(value = "mainTransactionManager")
public void store(Review review) {
    mainSessionFactory.getCurrentSession().saveOrUpdate(review);

}

@Override
@Transactional(value = "mainTransactionManager")
public void delete(Long reviewId) {
    Review review = (Review)mainSessionFactory.getCurrentSession()
            .get(Review.class, reviewId);
    mainSessionFactory.getCurrentSession().delete(review);
}
}

最后,这是我在验证用户并获取crypto_key后尝试做的事情。

String jdbcUrl = "jdbc:hsqldb:./ReviewDatabase/data2;crypt_key=" + secret + ";crypt_type=AES";
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
    .applySetting("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
    .applySetting("hibernate.show_sql", "true")
    .applySetting("hibernate.hbm2ddl.auto","update")
    .applySetting("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
    .applySetting("hibernate.connection.url", jdbcUrl)
    .applySetting("hibernate.connection.username", "reviewer")
    .applySetting("hibernate.connection.password", "$kelatonKey")
    .buildServiceRegistry();

    SessionFactory mainSessionFactory = new MetadataSources(serviceRegistry)
        .addAnnotatedClass(com.company.domain.Review.class)
        .addAnnotatedClass(com.company.domain.Person.class)
        .addAnnotatedClass(com.company.domain.Thing.class)
        .addAnnotatedClass(com.company.domain.Thing1.class)
        .addAnnotatedClass(com.company.domain.Thing2.class)
        .buildMetadata()
        .buildSessionFactory();
    org.springframework.orm.hibernate4.HibernateTransactionManager htm = 
            (HibernateTransactionManager)context.getBean("mainTransactionManager");
    context.getAutowireCapableBeanFactory().initializeBean(mainSessionFactory, "mainSessionFactory"); 
    htm.setSessionFactory(mainSessionFactory);  

但是,对此,对上述对象的第一个查询会产生org.hibernate.HibernateException: No Session found for current thread

如何在hibernate初始化之后长时间更改jdbcurl,注入依赖关系并发生其他各种类型的tom-foolery? 我一直在放弃这部分开发,希望谷歌最终能够通过,但我没有想要搜索的想法。所有答案都将以羞怯的态度接受:)

3 个答案:

答案 0 :(得分:0)

我想知道这是否有用,Can I replace a Spring bean definition at runtime?,您可以将bean属性设置为开始,然后在运行时更改bean。

答案 1 :(得分:0)

因此,配方的缺失部分是LocalSessionFactoryBean。它得到了sessionFactory设置,所以我可以替换初始化时创建的sessionFactories。 这是我必须从问题中改变的代码

    org.springframework.orm.hibernate4.HibernateTransactionManager htm = 
            (HibernateTransactionManager)context.getBean("mainTransactionManager");
    Class<?>[] classes = new Class<?>[5];
    classes[0] =  com.company.domain.Thing1.class;
    classes[1] =  com.company.domain.Thing2.class;
    classes[2] =  com.company.domain.Person.class;
    classes[3] =  com.company.domain.Thing.class;
    classes[4] =  com.company.domain.Review.class;

    String jdbcUrl = "jdbc:hsqldb:./ReviewDatabase/data3;crypt_key=" + secret + ";crypt_type=AES";

    java.util.Properties hibernateProperties = new java.util.Properties();
    hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    hibernateProperties.setProperty("hibernate.show_sql", "true");
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto","update");
    hibernateProperties.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
    hibernateProperties.setProperty("hibernate.connection.url", jdbcUrl);
    hibernateProperties.setProperty("hibernate.connection.username", "reviewer");
    hibernateProperties.setProperty("hibernate.connection.password", "$kelatonKey");


    LocalSessionFactoryBean slfb = new LocalSessionFactoryBean();
    slfb.setHibernateProperties(hibernateProperties);
    slfb.setAnnotatedClasses(classes);
    try {
        slfb.afterPropertiesSet();
    } catch (IOException e) {
        Log.warn("Cannot connection to application database");
        Log.write(e.getLocalizedMessage());
        Log.write(e.getStackTrace());
        return;
    }
    SessionFactory mainSessionFactory = slfb.getObject();
    context.getAutowireCapableBeanFactory().initializeBean(mainSessionFactory, "mainSessionFactory");

    htm.setSessionFactory(mainSessionFactory);  
    for(ListenForNewSessionFactory dao : daos){
        dao.setNewSessionFactory(mainSessionFactory);
    }

我让每个Dao实现了一个接口来设置sessionFactory,并让每个人在初始化时将自己添加到静态列表中。它不是非常可重复使用,但它确实有效。

答案 2 :(得分:0)

我使用了以下hack - 无论我需要SessionFactory,我都使用SessionFactoryFactory(下面)代替 - 实际使用的唯一SessionFactory方法。

@Component
public class SessionFactoryFactory {
    @Autowired
    private LocalSessionFactoryBean sessionFactoryBean;

    @Autowired
    private DriverManagerDataSource dataSource;

    private SessionFactory sessionFactory;

    private SessionFactory getSessionFactory() {
        if (null == sessionFactory) {
            sessionFactory = sessionFactoryBean.getObject();
        }
        return sessionFactory;
    }

    public Session openSession() {
        return getSessionFactory().openSession();
    }

    public void updateDataSourceUrl() throws IOException {
        sessionFactory = null;
        sessionFactoryBean.afterPropertiesSet();
    }
}