且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在persistence.xml和spring配置文件中配置数据源之间的区别

更新时间:2021-10-02 22:29:39

如果你在JavaEE容器中,它会产生很大的不同。

除了个人偏好之外,如果你按照第二种方法进行一些修改,你会好得多。

More than personal preference, you're much better off if you follow the second approach with a few modifications.

In第一种情况,您正在创建自己的连接池,并且不会从容器中的现有连接池中获利。因此,即使您将容器配置为例如最多20个同时连接到数据库,也无法保证最大值,因为此新连接池不受您的配置限制。此外,您不会从容器为您提供的任何监控工具中获利

In the first case, you're creating your own connection pool and do not profit from the existing connection pool in the container. Thus even if you configured your container to, say, a max of 20 simultaneous connections to the database, you can't guarantee this max as this new connection pool is not restrained by your configuration. Also, you don't profit from any monitoring tools your container provides you.

在第二种情况下,您也是创建自己的连接池,具有与上述相同的缺点。但是,您可以隔离此spring bean的定义并仅在测试运行中使用它。

In the second case, you're also creating your own connection pool, with the same disadvantages as above. However, you can isolate the definition of this spring bean and only use it in test runs.

您***的选择是通过JNDI查找容器的连接池即可。然后,您一定要尊重容器中的数据源配置。

Your best bet is to look up the container's connection pool via JNDI. Then you are sure to respect the data source configurations from the container.

<!-- datasource-test.xml -->
<bean id="domainDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
   <property name="driverClass" value="${db.driver}" />
   <property name="jdbcUrl" value="${datasource.url}" />
   <property name="user" value="${datasource.username}" />
   <property name="password" value="${datasource.password}" />
   <property name="initialPoolSize" value="5"/>
   <property name="minPoolSize" value="5"/>
.....
</bean>



在部署到JavaEE容器时使用此



Use this when deploying to a JavaEE container

<!-- datasource.xml -->
<jee:jndi-lookup id="domainDataSource" jndi-lookup="jndi/MyDataSource" />




  • 请记住设置 JEE架构

  • 虽然Tomcat不是一个完整的JavaEE容器,但它确实通过JNDI管理数据源,所以这个答案仍然适用。