JPA2运行时数据库连接

时间:2012-06-25 18:14:40

标签: runtime jpa-2.0 jta

我在我当前的网络项目中使用JP2。我的主数据库包含主要实体。要在此DB上连接,我使用JTA数据源定义了一个Persitence单元:

Persistance.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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_2_0.xsd">
<persistence-unit name="MyPU" transaction-type="JTA">

    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

    <jta-data-source>MyDB</jta-data-source>

    <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
        <property name="eclipselink.logging.level" value="FINE"/>
        <property name="eclipselink.logging.parameters" value="true"/>
        <property name="eclipselink.logging.logger" value="ServerLogger"/>
        <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
    </properties>
</persistence-unit>
</persistence>

和sun-resources.xml中定义的JTA数据源:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="org.postgresql.ds.PGSimpleDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="post-gre-sql_mydb_mypool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="5432"/>
        <property name="databaseName" value="mydb"/>
        <property name="User" value="myuser"/>
        <property name="Password" value="mypass"/>
        <property name="URL" value="jdbc:postgresql://localhost:5432/mydb"/>
        <property name="driverClass" value="org.postgresql.Driver"/>
        <property name="characterEncoding" value="UTF-8" />
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="MyDB" object-type="user" pool-name="post-gre-sql_mydb_mypoll"/>
</resources>

这就是我在DAO类上访问数据库的方式(@ManagedBeans和@SessionScoped):

@ManagedBean(name = "pageDao")
@SessionScoped
public class PageDao implements Serializable {

    @Resource
    private UserTransaction utx = null;

    @PersistenceUnit(unitName = "MyPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public List<PageEnt> getAll() { ... }

    public PageEnt getOne(long pageId) { ... }

    public void addPage(PageEnt newPage) throws RollbackFailureException, PreexistingEntityException, Exception { ... }

    public PageEnt update(PageEnt page) throws RollbackFailureException, NonexistentEntityException, Exception { ... }

    public void remove(PageEnt page) throws RollbackFailureException, Exception { ... }
}

其中一个实体(客户)具有在单独的(每个客户)数据库上进行连接的属性,这些属性在运行时定义。这些属性包括:

  • 数据库名称
  • 主机和端口
  • 用户和密码

我的问题是:

  • 如何在运行时有效地创建数据库连接?
  • 如果没有定义每个客户PersistanceUnit和Datasources(在部署时定义),如何从容器管理的资源创建新的EntityManager?
  • 如果我必须手动处理EntityManagerFactory(女巫,正如我在大学里学到的那样,是一个沉重而广阔的对象),我该如何有效地做到这一点?有没有好的做法或模式?
  • DAO模式如何工作?我的DAO类如何获得EntityManager?

非常感谢巴西。

1 个答案:

答案 0 :(得分:0)

可以在运行时在多个数据源之间切换。它由Spring AbstractRoutingDataSource提供。需要覆盖#determineCurrentLookupKey()方法,该方法将返回一个键以决定需要连接的特定数据源。还应该有弹簧配置,映射每个可能的键和要连接的相应数据源。有点像什么    <jee:jndi-lookup id="DataSource_Client1" jndi-name="DataSource_Client1" /> <jee:jndi-lookup id="DataSource_Client2" jndi-name="DataSource_Client" />
<bean id="DynamicDataSource" class="concrete implementation class name of AbstractRoutingDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="Client1" value-ref="DataSource_Client1" />
<entry key="Client2" value-ref="DataSource_Client2" />
</map>
</property>
</bean>

对此Dynamic DataSource

的可能引用

希望这能回答你的一个问题