简体   繁体   English

使用休眠在运行时为derby数据库设置bootPassword

[英]set bootPassword for derby database at runtime using hibernate

I use Hibernate and Derby. 我使用Hibernate和Derby。

I have a hibernate.cfg.xml and all I did for working with db waas to get a Session : 我有一个hibernate.cfg.xml,我所做的所有与db waas一起使用来获取Session的工作:

  return new AnnotationConfiguration().configure( "files/hibernate.cfg.xml"   ).buildSessionFactory().getCurrentSession();

my hibernate.cfg.xml containes 我的hibernate.cfg.xml包含

   <property name="connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
   <property name="connection.url">jdbc:derby:crmdb;create=true</property>

and some other properties and mappings for entity classes. 以及实体类的其他一些属性和映射。

now I want to set dataEncryption for derby db and bootPassword at runtime. 现在我想在运行时为derby db和bootPassword设置dataEncryption。

I changed hibernate.cfg.xml : 我改变了hibernate.cfg.xml:

    <property name="connection.url">jdbc:derby:crmdb;create=true;dataEncryption=true;bootPassword=myPass</property>

and everything was ok. 一切都还好。

Now I want to set bootPassword at runtime, exby reading from an environment variable. 现在,我想在运行时设置bootPassword,例如从环境变量中读取。 that´s the problem! 那就是问题所在! when I delete "connection.url" from hibernate.cfg.xml and trying to set it inside my code, this error ocurres : 当我从hibernate.cfg.xml删除“ connection.url”并尝试在我的代码中设置它时,发生此错误:

 java.lang.UnsupportedOperationException: The application must supply JDBC connections

and if I delete only bootPassword, it can not connect to db. 如果我仅删除bootPassword,它就无法连接到数据库。

any idea ? 任何想法 ?

It resolved ! 解决了!

I should set "hibernate.connection.url" instead of "connection.url" ! 我应该设置“ hibernate.connection.url”而不是“ connection.url”!

You need to modify the configuration before building the sessionFactory: 您需要在构建sessionFactory之前修改配置:

private SessionFactory sessionFactory;

public SessionFactory getSessionFactory(){
    if(sessionFactory==null){
        Configuration configuration = new AnnotationConfiguration().configure( "files/hibernate.cfg.xml"   );
        configuration.setProperty("hibernate.connection.url", "jdbc:derby:crmdb;create=true;dataEncryption=true;bootPassword="+password);
        configuration.configure();
        sessionFactory = configuration.buildSessionFactory();
    }
    return sessionFactory;
}

Other remark : you must avoid to recreate a new SessionFactory everytime (it take a lot of time, consume lot of resources and it's useless). 其他说明:您必须避免每次都重新创建一个新的SessionFactory(这会花费很多时间,消耗大量资源并且没有用)。 ie You must create one sessionFactory for each bootPassword (since it's the only dynamic part) and if you only have one bootPassword - ie one single DB - then your sessionFactory can/must be a singleton. 即您必须为每个bootPassword创建一个sessionFactory(因为它是唯一的动态部分),并且如果只有一个bootPassword-即一个DB-那么sessionFactory可以/必须是单例。

ref REF

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM