pau*_*chf 11 java xml hibernate persistence.xml shiro
编辑:不重复但差不多
我想让我的应用程序persistence.xml类似于
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="appName" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="${db.dialect'}"/>
<property name="javax.persistence.jdbc.driver" value="${db.driver}"/>
<property name="javax.persistence.jdbc.user" value="${db.user}"/>
<property name="javax.persistence.jdbc.password" value="${db.password}"/>
<property name="javax.persistence.jdbc.url" value="${db.url}"/>
</properties>
</persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)
从源文件夹中某处的简单文本文件中获取这些占位符值.
我读到了使用Spring做的可能性
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/jdbc.properties</value>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
但是在这里我们不使用Spring,只使用Hibernate和一些Primefaces.
可能吗?
谢谢!
编辑:我没有提到一些东西,但作为参考,我也使用Shiro Security和Ant来做一些事情.我将发布解决方案作为答案.这使我的项目有3个不同的文件与数据库参数:
Dav*_*que 24
persistence.xml
您可以在标准属性文件(key = value)中定义它们,并将Properties
对象传递给createEntityManagerFactory()
方法,而不是在其中定义属性,例如:
Properties props = new Properties();
props.load(new FileInputStream("/some/path/persistence.properties"));
EntityManagerFactory factory = Persistence.createEntityManagerFactory("appName", props);
Run Code Online (Sandbox Code Playgroud)
我编辑提到我正在使用 Shiro Security,它也需要一些数据库参数。我让它只需要 1 个数据库参数位置,将这些参数保留在 context.xml 中并在其他参数中引用它。
1)Ant读取context.xml
Context.xml 有
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Other stuff... -->
<!-- Shiro's -->
<Resource name="jdbc/postgres" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://url-to-db/database"
username="user" password="pass" />
</Context>
Run Code Online (Sandbox Code Playgroud)
在 Ant build.xml 中使用
<xmlproperty file="/path/to/context.xml" keepRoot="false" semanticAttributes="true" includeSemanticAttribute="true" />
Run Code Online (Sandbox Code Playgroud)
然后使用访问它
<target name="init-flyway">
<property name="flyway.url" value="${Resource.url}" />
<property name="flyway.user" value="${Resource.username}" />
<property name="flyway.password" value="${Resource.password}" />
<!-- stuff stuff stuff -->
</target>
Run Code Online (Sandbox Code Playgroud)
2)persistence.xml读取context.xml
可以使用上下文的数据存储
<non-jta-data-source>java:/comp/env/jdbc/postgres</non-jta-data-source>
Run Code Online (Sandbox Code Playgroud)
因此,我将 3 个数据库参数删除为 1 个。
谢谢您的帮助!
归档时间: |
|
查看次数: |
16207 次 |
最近记录: |