|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.
You think you know what’s in your data. But do you? Most organizations are now aware of the business intelligence represented by their data. Data science stands to take this to a level you never thought of – literally. The techniques of data science, when used with the capabilities of Big Data technologies, can make connections you had not yet imagined, helping you discover new insights and ask new questions of your data. In his session at @ThingsExpo, Sarbjit Sarkaria, data science team lead ...
May. 2, 2016 11:00 PM EDT Reads: 984
In his session at @ThingsExpo, Chris Klein, CEO and Co-founder of Rachio, will discuss next generation communities that are using IoT to create more sustainable, intelligent communities. One example is Sterling Ranch, a 10,000 home development that – with the help of Siemens – will integrate IoT technology into the community to provide residents with energy and water savings as well as intelligent security. Everything from stop lights to sprinkler systems to building infrastructures will run ef...
May. 2, 2016 07:00 PM EDT Reads: 1,045
SYS-CON Events announced today that Peak 10, Inc., a national IT infrastructure and cloud services provider, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Peak 10 provides reliable, tailored data center and network services, cloud and managed services. Its solutions are designed to scale and adapt to customers’ changing business needs, enabling them to lower costs, improve performance and focus inter...
May. 2, 2016 06:30 PM EDT Reads: 1,300
Artificial Intelligence has the potential to massively disrupt IoT. In his session at 18th Cloud Expo, AJ Abdallat, CEO of Beyond AI, will discuss what the five main drivers are in Artificial Intelligence that could shape the future of the Internet of Things. AJ Abdallat is CEO of Beyond AI. He has over 20 years of management experience in the fields of artificial intelligence, sensors, instruments, devices and software for telecommunications, life sciences, environmental monitoring, process...
May. 2, 2016 05:15 PM EDT Reads: 995
Increasing IoT connectivity is forcing enterprises to find elegant solutions to organize and visualize all incoming data from these connected devices with re-configurable dashboard widgets to effectively allow rapid decision-making for everything from immediate actions in tactical situations to strategic analysis and reporting. In his session at 18th Cloud Expo, Shikhir Singh, Senior Developer Relations Manager at Sencha, will discuss how to create HTML5 dashboards that interact with IoT devic...
May. 2, 2016 05:00 PM EDT Reads: 1,096
So, you bought into the current machine learning craze and went on to collect millions/billions of records from this promising new data source. Now, what do you do with them? Too often, the abundance of data quickly turns into an abundance of problems. How do you extract that "magic essence" from your data without falling into the common pitfalls? In her session at @ThingsExpo, Natalia Ponomareva, Software Engineer at Google, will provide tips on how to be successful in large scale machine lear...
May. 2, 2016 03:45 PM EDT Reads: 1,349
The IoTs will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, will demonstrate how to move beyond today's coding paradigm and share the must-have mindsets for removing complexity from the development proc...
May. 2, 2016 03:00 PM EDT Reads: 372
SYS-CON Events announced today that Ericsson has been named “Gold Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. Ericsson is a world leader in the rapidly changing environment of communications technology – providing equipment, software and services to enable transformation through mobility. Some 40 percent of global mobile traffic runs through networks we have supplied. More than 1 billion subscribers around the world re...
May. 2, 2016 02:45 PM EDT Reads: 1,093
You deployed your app with the Bluemix PaaS and it's gaining some serious traction, so it's time to make some tweaks. Did you design your application in a way that it can scale in the cloud? Were you even thinking about the cloud when you built the app? If not, chances are your app is going to break. Check out this webcast to learn various techniques for designing applications that will scale successfully in Bluemix, for the confidence you need to take your apps to the next level and beyond.
May. 2, 2016 12:00 PM EDT Reads: 1,551
There is an ever-growing explosion of new devices that are connected to the Internet using “cloud” solutions. This rapid growth is creating a massive new demand for efficient access to data. And it’s not just about connecting to that data anymore. This new demand is bringing new issues and challenges and it is important for companies to scale for the coming growth. And with that scaling comes the need for greater security, gathering and data analysis, storage, connectivity and, of course, the...
May. 2, 2016 11:45 AM EDT Reads: 964
SYS-CON Events announced today that Fusion, a leading provider of cloud services, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Fusion, a leading provider of integrated cloud solutions to small, medium and large businesses, is the industry's single source for the cloud. Fusion's advanced, proprietary cloud service platform enables the integration of leading edge solutions in the cloud, including cloud...
May. 2, 2016 10:00 AM EDT Reads: 2,637
Digital payments using wearable devices such as smart watches, fitness trackers, and payment wristbands are an increasing area of focus for industry participants, and consumer acceptance from early trials and deployments has encouraged some of the biggest names in technology and banking to continue their push to drive growth in this nascent market. Wearable payment systems may utilize near field communication (NFC), radio frequency identification (RFID), or quick response (QR) codes and barcodes...
May. 2, 2016 09:15 AM EDT Reads: 874
The increasing popularity of the Internet of Things necessitates that our physical and cognitive relationship with wearable technology will change rapidly in the near future. This advent means logging has become a thing of the past. Before, it was on us to track our own data, but now that data is automatically available. What does this mean for mHealth and the "connected" body? In her session at @ThingsExpo, Lisa Calkins, CEO and co-founder of Amadeus Consulting, will discuss the impact of wea...
May. 2, 2016 08:45 AM EDT Reads: 794
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
May. 2, 2016 06:30 AM EDT Reads: 2,547
The IoT has the potential to create a renaissance of manufacturing in the US and elsewhere. In his session at 18th Cloud Expo, Florent Solt, CTO and chief architect of Netvibes, will discuss how the expected exponential increase in the amount of data that will be processed, transported, stored, and accessed means there will be a huge demand for smart technologies to deliver it. Florent Solt is the CTO and chief architect of Netvibes. Prior to joining Netvibes in 2007, he co-founded Rift Technol...
May. 1, 2016 11:00 PM EDT Reads: 1,628
We’ve worked with dozens of early adopters across numerous industries and will debunk common misperceptions, which starts with understanding that many of the connected products we’ll use over the next 5 years are already products, they’re just not yet connected. With an IoT product, time-in-market provides much more essential feedback than ever before. Innovation comes from what you do with the data that the connected product provides in order to enhance the customer experience and optimize busi...
May. 1, 2016 05:00 PM EDT Reads: 1,089
SYS-CON Events announced today that Stratoscale, the software company developing the next generation data center operating system, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Stratoscale is revolutionizing the data center with a zero-to-cloud-in-minutes solution. With Stratoscale’s hardware-agnostic, Software Defined Data Center (SDDC) solution to store everything, run anything and scale everywhere...
May. 1, 2016 01:30 PM EDT Reads: 1,611
Angular 2 is a complete re-write of the popular framework AngularJS. Programming in Angular 2 is greatly simplified – now it's a component-based well-performing framework. This immersive one-day workshop at 18th Cloud Expo, led by Yakov Fain, a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay, will provide you with everything you wanted to know about Angular 2.
May. 1, 2016 01:00 PM EDT Reads: 1,785
SYS-CON Events announced today that Men & Mice, the leading global provider of DNS, DHCP and IP address management overlay solutions, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. The Men & Mice Suite overlay solution is already known for its powerful application in heterogeneous operating environments, enabling enterprises to scale without fuss. Building on a solid range of diverse platform support,...
May. 1, 2016 12:15 PM EDT Reads: 2,365
Whether your IoT service is connecting cars, homes, appliances, wearable, cameras or other devices, one question hangs in the balance – how do you actually make money from this service? The ability to turn your IoT service into profit requires the ability to create a monetization strategy that is flexible, scalable and working for you in real-time. It must be a transparent, smoothly implemented strategy that all stakeholders – from customers to the board – will be able to understand and comprehe...
May. 1, 2016 11:00 AM EDT Reads: 1,128