一般形式的数据容器
下面代码展示了一个一般形式的数据容器实例的创建(DataContext):这里的DataContext很类似Spring中的对象工厂的管理形式。
这种方式可以用于独立程序中,用户来指定的“session”标记。在网站程序,正确的数据容器通常需要暴露到session或外部的请求线程中,可以供需要它的时候获取它(接下来将讨论网站程序中的使用)。为每一个请求创建一个数据容器是很不适合的。
在网站程序获取session形式的数据容器
网站程序可以配置自动为每个HttpSession创建数据容器实例,并且设置它的session属性。参考下面代码从session获取它。
获取通过线程暴露的数据容器
一个应用程序可以绑定到当前执行线程的数据容器。后续的代码需要数据库访问时,可以获取这个数据容器,并且无需考虑环境。可以应用各种应用中(web、独立程序等)。之前暴露的数据容器可以通过DataContext.getThreadDataContext()静态方法来调用。如果当前进程没有暴露数据容器,这个方法将抛出IllegalStateException:
高级的多数据域(DataDomains) 方式应用
Cayenne can be configured to support mass database hosting. This is a so-called Application Service Provider (ASP) scenario. Basic architecture of such setup is a single application supporting multiple databases (or more generally - data sources), each one with same or similar schema. Each data source corresponds to an individual ASP "customer" using the system. Each customer has a number of users that will log in to the system and are only allowed to view data from their data source.
This approach, though not required for most normal applications, could be quiet common and powerful in some enterprise systems. To implement it, each DataContext must be limited to access only a relevant subset of datasources.
Considering that behind the scenes a source of DataContext instances is an object called DataDomain, Cayenne allows creation of multiple DataDomains per project. Each DataDomain would support a single "customer". Creation of DataContext in this case is done using DataDomain name as a parameter: