| Apache Cayenne > Index > Cayenne FAQ > Setting Database Connection |
Most common way to provide database connection information to Cayenne is by entering it for each DataNode in CayenneModeler. Another alternative is setting JNDI name of a DataSource in the Modeler so that Cayenne could use a DataSource provided by the container. This approach is described in Cayenne documentation.
Still in some cases an application may need to set connection information in a running application dynamically. This rarely makes sense in multiuser web applications, as giving each user her own connection (and Cayenne access stack) is not scaleable, so web applications usually rely on shared connection pools. However this is a quite common situation in single-user client applications, unit test suites, etc.
A solution is simple - build an instance of a javax.sql.DataSource in the code, locate an appropriate DataNode, and replace its DataSource with the one you just built. Any DataSource implementation will do, but Cayenne already provides two ready to use classes - PoolManager
(pooled DataSource) and DriverDataSource
(simple DataSource). E.g.:
DataSource dataSource = new PoolManager("org.postgresql.Driver", "jdbc:postgresql://localhost:5432/cayenne", 1, 5, "user", "password"); Configuration config = Configuration.getSharedConfiguration(); DataDomain domain = config.getDomain(); DataNode node = domain.getNode("DB1"); node.setDataSource(dataSource);
This is probably the most straightforward solution. Other possibilities include using a custom ConfigLoaderDelegate, or implementing a custom DataSourceFactory![]()