【第二章 DataContext 】1 获取数据容器

本文介绍了Apache Cayenne框架中的数据容器(DataContext)管理方法,包括独立程序与网站程序中的数据容器创建及获取方式,以及如何实现多数据域的支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般形式的数据容器

下面代码展示了一个一般形式的数据容器实例的创建(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:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值