[英]set bootPassword for derby database at runtime using hibernate
我使用Hibernate和Derby。
我有一個hibernate.cfg.xml,我所做的所有與db waas一起使用來獲取Session的工作:
return new AnnotationConfiguration().configure( "files/hibernate.cfg.xml" ).buildSessionFactory().getCurrentSession();
我的hibernate.cfg.xml包含
<property name="connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
<property name="connection.url">jdbc:derby:crmdb;create=true</property>
以及實體類的其他一些屬性和映射。
現在我想在運行時為derby db和bootPassword設置dataEncryption。
我改變了hibernate.cfg.xml:
<property name="connection.url">jdbc:derby:crmdb;create=true;dataEncryption=true;bootPassword=myPass</property>
一切都還好。
現在,我想在運行時設置bootPassword,例如從環境變量中讀取。 那就是問題所在! 當我從hibernate.cfg.xml刪除“ connection.url”並嘗試在我的代碼中設置它時,發生此錯誤:
java.lang.UnsupportedOperationException: The application must supply JDBC connections
如果我僅刪除bootPassword,它就無法連接到數據庫。
任何想法 ?
解決了!
我應該設置“ hibernate.connection.url”而不是“ connection.url”!
您需要在構建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;
}
其他說明:您必須避免每次都重新創建一個新的SessionFactory(這會花費很多時間,消耗大量資源並且沒有用)。 即您必須為每個bootPassword創建一個sessionFactory(因為它是唯一的動態部分),並且如果只有一個bootPassword-即一個DB-那么sessionFactory可以/必須是單例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.