|By Daniel O'Connor||
|June 1, 2000 12:00 AM EDT||
Say you're writing an Enterprise JavaBean that represents a persistent object, such as a customer or a product. You have two choices for getting data (such as customer name and product number) from the bean to the database and back:
- You can let the bean's runtime environment its container, in EJB speak do the heavy lifting for you....
- ....or you can provide the logic yourself along with your bean.
According to the current version of the Enterprise JavaBeans Specification (v1.1), a compliant EJB container isn't required to provide any support for mapping the container-managed fields to a database schema. For instance, it could use Java serialization to save the beans to a file. Most if not all commercial and open-source containers will map fields to table columns in a database. But some will do it better than others. You'll have trouble with some products, for example, if you want to map your bean to multiple rows in multiple tables.
In fact, you probably do want to map your bean to multiple rows in multiple tables. Your beans should be coarse-grained, managing their own dependent objects. Your order bean should have line items implemented as a helper class, rather than as references to line-item EJBs. Your customer bean should have addresses rather than references to address beans. The overhead of bean-to-bean calls between an order and its line items, or a customer and its addresses, would be prohibitive. Your EJB server can provide you with many services, such as declarative transactions, security, and even load balancing and failover. But there's no free lunch, and the price you pay is indirection. Every call you make goes through a layer whose purpose is to provide these services (see Figure 1). Managing dependent objects reduces the frequency of trips through this indirection layer (see Figure 2). And a bean with multiple dependent objects needs to be stored in multiple tables, in multiple rows, if you want to maintain a normalized schema.
Technically, bean-managed persistence doesn't mean you have to write your own database access code. It just means the bean, rather than the container, provides the persistence logic. Several good object-relational mapping tools are on the market, and they can be portable from server to server along with your bean. But you may find it impossible to use these tools because of cost (some have runtime fees and/or a hefty per-developer price tag), distribution practicalities or reasons of your own. This article will tell you what you need to do to write your own persistence for a coarse-grained entity bean.
Requirements for Dependent Objects
An efficient implementation of bean-managed persistence for dependent objects will have two features:
- Partitioned storage logic
Load-on-demand means that the dependent objects aren't loaded until they're actually needed. The EJB framework will call a function in your entity bean to indicate that persistent data should be made available to the bean's business logic. The bean could load the dependent data at this point. But if the business logic doesn't make use of certain dependent data during the current transaction, that database access was wasted. For instance, changing a customer's credit rating may not require access to any address, so the addresses shouldn't be loaded. If the dependent data is accessed, it can be loaded at that time. (This is also known as lazy loading.) Partitioned storage logic is necessary so that the bean updates the database the way a relational database expects: new data is inserted, changed data is updated, discarded data is deleted and unchanged data is left alone (see Figure 3). The alternative wiping out the records and reinserting them is too horrible even to contemplate.
A Good Idiom
To implement load-on-demand, you could scatter calls throughout your business logic to functions with names like "ensureAddressListLoaded" and "ensureLineItemListLoaded" that is, if you want to be the poster child for ugly code. And to store your dependent objects to the database, you could have each object keep track of its status: NEW, UPDATED, DELETED or UNMODIFIED. As you totaled the line items in a purchase order, you'd need to check each object to see if it had been deleted (see Figure 4). Don't forget, or you're going to have some unhappy customers.
A better idiom is to group the logic related to persistence with a collection class. Your business logic for an order probably works with a list of line items. To delete an object, the most natural thing to do is probably to remove it from the list. To add an object, the most natural thing is to append it to the list. And simply calling a method on the list should be the signal to your persistence logic that the items in the list need to be loaded from the database. If you use a smart list that knows how to do these things, nothing else needs to be done from the perspective of the business logic programmer. In the example of totaling line items in a purchase order, you'd simply iterate through the objects in the list (see Figure 5).
Behind the scenes, a smart list implementation is keeping track of an "isLoaded" variable. When the list is accessed, it checks this variable first to see if the data needs to be loaded from the database. If so, it loads it. It keeps a set of references to all the objects it loads to distinguish them from new objects added to the list. If an object is removed from the list, it's added to an internal list of deleted objects. This deleted objects list is used by the persistence logic, but not, typically, by the business logic programmer.
The Proxy List
The smart list needs a layer of indirection between the list interface and the actual list storage. At this layer a method call on the list to remove objects will first add those objects to the internal deleted objects list. Also, a call to any function will check to see if the list data has been loaded. One possible way to gain this indirection is simply to implement the java.util.List interface and delegate the calls to a private internal "backing" list. A more elegant way is to use the java.lang.reflect.Proxy class newly available in JDK 1.3. (Note: Using the Proxy class limits your bean's portability to servers that support JDK 1.3. All the techniques and code discussed in this article are easily adapted to the "delegation list" compatible with earlier JDKs.)
The Proxy class dynamically creates an implementation of an interface that will automatically forward all its calls to a middle layer called InvocationHandler (also in package java.lang.reflect). In a subclass of InvocationHandler you can forward the method call (or not), take action before or after forwarding it, alter its parameters and change the returned object (see Figure 6). As you can see, this is more than enough functionality to implement our smart list. The uses for this Proxy are many: it can be used to handle user interface events and to provide a "poor man's multiple inheritance," and has even been used to implement an open-source EJB server, EJBoss. (For more information on the Proxy and InvocationHandler classes, see the article at http://java.sun.com/products/jfc/tsc/articles/generic-listener2/index.html on Sun's Web site.)
Take a look at ListInvocationHandler (see Listing 1). It's the smart list implementation that keeps track of deleted objects, the set of original objects and whether the data has been loaded from the database. It also takes as a constructor parameter its "backing" list so that any class implementing the List interface (LinkedList or ArrayList) can be used, depending on how the data is typically accessed. The main functionality is in the invoke method. Here I check to make sure the data has been loaded from the database. I also check for any List function that removes an object so I can make a copy to use for calling "delete" later on the database. An important point: several List functions will return a reference to the backing list unless these too are interposed on. Any method that returns an Iterator (which points to the backing list) must instead be made to return an Iterator pointing to the interposed list. I did this using you guessed it another Proxy (see Listing 2). Any method that returns a Collection must either be interposed on or made unmodifiable.
My smart list implementation uses two persistence-specific interfaces (see Figure 7). The first, PersistentOperations (see Listing 3), is implemented by the smart list itself (in ListInvocationHandler). It's for list operations needed by the bean's persistence plumbing, rather than the business logic. You can get a list of deleted objects to actually delete them. You can get the set of original objects to decide between insert and update operations. You can add an object to the list so that it's tagged as an original object rather than a new one. You can tell the list that the bean has been asked to save itself to persistent storage, and to take whatever actions are necessary. For symmetry more than need, you can also ask the list to load itself from persistent storage. Typically, you'll let the list decide this for itself.
The second persistence-specific interface used by the list is DataStore (see Listing 4). Although your business logic can treat the smart list as a regular list, you need to put the SQL somewhere, and this interface is the gateway to that "somewhere." Your bean will pass an implementation of this interface to the smart list factory (DemandListFactory; see Listing 5). When the list needs to save or restore its data, it will call methods in this interface, passing a reference to its PersistentOperations interface.
A simplified example of using a proxy list with an EJB with bean-managed persistence is available on the Java Developer's Journal Web site. The bean implements a customer-has-line-items model. A customer has an ID and a name, and an unlimited number of line items of products he or she has ordered. In order to give the smart list a workout, I've written functions so the business logic programmer can add, delete or change a line item, and use the entire set of line items at once. The list is initialized when the bean is created (a new customer record is inserted) or loaded (an existing customer record is read from the database). An anonymous DataStore implementation is passed to the DemandListFactory, which will call bean methods whenever DataStore methods are called by the list.
One bean method will do a simple select on the database table where line items are stored. As it iterates through the result set, it calls the PersistentOperations's addFromStore method, which will indicate to the list that the object already exists in the database and needs to be updated, not inserted, when the list is stored. Another bean method that stores the list is only slightly more complicated. It must use the information available from the PersistentOperations interface to partition the objects into three sets: insertions, updates and deletes. You'll notice that I'm using an isModified function to further partition updates from unmodified instances. It's possible to do this in the smart list as well by keeping a copy of each original object and then comparing it to the object's state just before the database update. There are disadvantages to this technique, however, depending on the memory required to keep copies of those objects and the processing time required to compare object states. In any case, implementing this is beyond the scope of this article.
To test my Customer implementation, I've included a stateless session EJB that will give it a good workout. Fronting an entity EJB with a "business process" session, EJB is a common design pattern. Here it allows us to include multiple adds, deletes, updates and totals within one transaction. Since the typical EJB server will load and store persistent data on transaction boundaries (load when the transaction begins and store when it ends), this is important for our testing. Obviously, the stateless session EJB isn't a good example of an actual business process.
It isn't difficult to write an efficient, easy-to-use Enterprise JavaBean using bean-managed persistence. Well, what I should really say is that it's not much harder than writing the SQL code that your bean will use. If you need to roll your own persistence for EJBs, there's no better place for the persistence logic than a collection class. In this case we used a list, but the same technique would work for a Set or a Map, or even a tree document, depending on your needs. And if your target market allows you to write to the JDK 1.3, the new Proxy class can increase the expressiveness and effectiveness of your code.
If you’re responsible for an application that depends on the data or functionality of various IoT endpoints – either sensors or devices – your brand reputation depends on the security, reliability, and compliance of its many integrated parts. If your application fails to deliver the expected business results, your customers and partners won't care if that failure stems from the code you developed or from a component that you integrated. What can you do to ensure that the endpoints work as expect...
Oct. 1, 2016 04:30 AM EDT Reads: 1,796
Just over a week ago I received a long and loud sustained applause for a presentation I delivered at this year’s Cloud Expo in Santa Clara. I was extremely pleased with the turnout and had some very good conversations with many of the attendees. Over the next few days I had many more meaningful conversations and was not only happy with the results but also learned a few new things. Here is everything I learned in those three days distilled into three short points.
Oct. 1, 2016 04:00 AM EDT Reads: 5,471
WebRTC adoption has generated a wave of creative uses of communications and collaboration through websites, sales apps, customer care and business applications. As WebRTC has become more mainstream it has evolved to use cases beyond the original peer-to-peer case, which has led to a repeating requirement for interoperability with existing infrastructures. In his session at @ThingsExpo, Graham Holt, Executive Vice President of Daitan Group, will cover implementation examples that have enabled ea...
Oct. 1, 2016 04:00 AM EDT Reads: 1,653
SYS-CON Events announced today that ReadyTalk, a leading provider of online conferencing and webinar services, has been named Vendor Presentation Sponsor at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. ReadyTalk delivers audio and web conferencing services that inspire collaboration and enable the Future of Work for today’s increasingly digital and mobile workforce. By combining intuitive, innovative tec...
Oct. 1, 2016 04:00 AM EDT Reads: 3,122
There is growing need for data-driven applications and the need for digital platforms to build these apps. In his session at 19th Cloud Expo, Muddu Sudhakar, VP and GM of Security & IoT at Splunk, will cover different PaaS solutions and Big Data platforms that are available to build applications. In addition, AI and machine learning are creating new requirements that developers need in the building of next-gen apps. The next-generation digital platforms have some of the past platform needs a...
Oct. 1, 2016 03:00 AM EDT Reads: 1,970
Fifty billion connected devices and still no winning protocols standards. HTTP, WebSockets, MQTT, and CoAP seem to be leading in the IoT protocol race at the moment but many more protocols are getting introduced on a regular basis. Each protocol has its pros and cons depending on the nature of the communications. Does there really need to be only one protocol to rule them all? Of course not. In his session at @ThingsExpo, Chris Matthieu, co-founder and CTO of Octoblu, walk you through how Oct...
Oct. 1, 2016 03:00 AM EDT Reads: 2,447
Smart Cities are here to stay, but for their promise to be delivered, the data they produce must not be put in new siloes. In his session at @ThingsExpo, Mathias Herberts, Co-founder and CTO of Cityzen Data, will deep dive into best practices that will ensure a successful smart city journey.
Oct. 1, 2016 02:30 AM EDT Reads: 2,715
Businesses are struggling to manage the information flow and interactions between all of these new devices and things jumping on their network, and the apps and IT systems they control. The data businesses gather is only helpful if they can do something with it. In his session at @ThingsExpo, Chris Witeck, Principal Technology Strategist at Citrix, will discuss how different the impact of IoT will be for large businesses, expanding how IoT will allow large organizations to make their legacy ap...
Oct. 1, 2016 02:30 AM EDT Reads: 658
Adobe is changing the world though digital experiences. Adobe helps customers develop and deliver high-impact experiences that differentiate brands, build loyalty, and drive revenue across every screen, including smartphones, computers, tablets and TVs. Adobe content solutions are used daily by millions of companies worldwide-from publishers and broadcasters, to enterprises, marketing agencies and household-name brands. Building on its established design leadership, Adobe enables customers not o...
Oct. 1, 2016 02:30 AM EDT Reads: 550
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Oct. 1, 2016 02:15 AM EDT Reads: 759
SYS-CON Events announced today that Numerex Corp, a leading provider of managed enterprise solutions enabling the Internet of Things (IoT), will exhibit at the 19th International Cloud Expo | @ThingsExpo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Numerex Corp. (NASDAQ:NMRX) is a leading provider of managed enterprise solutions enabling the Internet of Things (IoT). The Company's solutions produce new revenue streams or create operating...
Oct. 1, 2016 02:15 AM EDT Reads: 2,139
24Notion is full-service global creative digital marketing, technology and lifestyle agency that combines strategic ideas with customized tactical execution. With a broad understand of the art of traditional marketing, new media, communications and social influence, 24Notion uniquely understands how to connect your brand strategy with the right consumer. 24Notion ranked #12 on Corporate Social Responsibility - Book of List.
Oct. 1, 2016 02:15 AM EDT Reads: 522
Why do your mobile transformations need to happen today? Mobile is the strategy that enterprise transformation centers on to drive customer engagement. In his general session at @ThingsExpo, Roger Woods, Director, Mobile Product & Strategy – Adobe Marketing Cloud, covered key IoT and mobile trends that are forcing mobile transformation, key components of a solid mobile strategy and explored how brands are effectively driving mobile change throughout the enterprise.
Oct. 1, 2016 01:45 AM EDT Reads: 523
As ridesharing competitors and enhanced services increase, notable changes are occurring in the transportation model. Despite the cost-effective means and flexibility of ridesharing, both drivers and users will need to be aware of the connected environment and how it will impact the ridesharing experience. In his session at @ThingsExpo, Timothy Evavold, Executive Director Automotive at Covisint, will discuss key challenges and solutions to powering a ride sharing and/or multimodal model in the a...
Oct. 1, 2016 01:15 AM EDT Reads: 728
In his general session at 18th Cloud Expo, Lee Atchison, Principal Cloud Architect and Advocate at New Relic, discussed cloud as a ‘better data center’ and how it adds new capacity (faster) and improves application availability (redundancy). The cloud is a ‘Dynamic Tool for Dynamic Apps’ and resource allocation is an integral part of your application architecture, so use only the resources you need and allocate /de-allocate resources on the fly.
Oct. 1, 2016 01:15 AM EDT Reads: 3,049
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lea...
Sep. 30, 2016 11:30 PM EDT Reads: 784
SYS-CON Events announced today that Roundee / LinearHub will exhibit at the WebRTC Summit at @ThingsExpo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. LinearHub provides Roundee Service, a smart platform for enterprise video conferencing with enhanced features such as automatic recording and transcription service. Slack users can integrate Roundee to their team via Slack’s App Directory, and '/roundee' command lets your video conference ...
Sep. 30, 2016 10:45 PM EDT Reads: 1,543
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
Sep. 30, 2016 10:00 PM EDT Reads: 1,266
"My role is working with customers, helping them go through this digital transformation. I spend a lot of time talking to banks, big industries, manufacturers working through how they are integrating and transforming their IT platforms and moving them forward," explained William Morrish, General Manager Product Sales at Interoute, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
Sep. 30, 2016 09:30 PM EDT Reads: 4,137
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, wh...
Sep. 30, 2016 09:00 PM EDT Reads: 4,066