Welcome!

Weblogic Authors: Yeshim Deniz, Elizabeth White, Michael Meiner, Michael Bushong, Avi Rosenthal

Related Topics: Weblogic

Weblogic: Article

Database Controls Best Practices

Avoiding Potential Pitfalls During The Development Life Cycle

Database controls extend the BEA WebLogic controls architecture to enable developers to easily interact with relational databases with maximum productivity. Utilizing a database control, a developer can quickly create methods to issue commands and retrieve data as required. Database controls can often be a more productive choice over other technology alternatives such as Enterprise JavaBeans (EJB).

While database controls were introduced in BEA WebLogic Workshop 7.0, they were not overly popular until the introduction of the 8.1 version of the WebLogic Platform and the dramatic increase in WebLogic Workshop functionality in the 8.1 release. Developers now approaching these controls for the first time can be forgiven for thinking that the controls are so simple that no best practices are required. In fact, the very simplicity of the control is what can often cause maintenance problems down the road as the database control is utilized in less than optimum ways.

This article will discuss a set of best practices pertaining to the use of the database controls. I assume that readers are already somewhat familiar with database controls and their usage; developers new to these controls are encouraged to review the help section in WebLogic Workshop, which contains an excellent overview.

Rather than complete a laundry list of do's and don'ts, we have opted to examine best practices in the context of a specific use case. In this hypothetical scenario we are a developer for a company called "Music Search" that runs a WebLogic portal that connects music industry employees with up-and-coming musical acts. As a developer for this site, we have been tasked to create a portlet that enables the site administrators to poll the site's users as a mechanism to gather information. The functionality consists of displaying a single question with multiple answers in the portlet. The user's response to the question is recorded; once answered, the percentage of responses for each answer is displayed to the user.

The database schema for the functionality required by the portlet will consist of three tables (see Figure 1).

The three tables are Question, Answer, and Response. The Question table is used to store an individual question while the Answer table is used to store the available choices for a given question. Finally, the Response table is used to store a user's answer to the displayed question. While linking the response table to the question table through the QUESTION_ID foreign key is not strictly necessary, it has been done here as a convenience for reporting.

Our first order of business is to create the logic required to add, update, and delete questions, answers, and responses. To accomplish this, we will create three classes to represent the domain model. The business logic will manage the relationship between the Question and Answer classes; however, the Response class will only be used for inserting new responses, as the users will utilize a reporting tool for analyzing polls.

A simplified UML diagram of our three domain classes is shown in Figure 2. Note that the Answer class is aggregated by the Question class and is only accessible through an instance of the Question class.

When To Use
One of the most important considerations of database controls is knowing when to use them within a given application. Database controls provide many of the same services that developers might alternatively use session and entity EJBs to encapsulate. Thus a common question would be, "when is it appropriate to use a database control versus other solutions?"

Database controls in their current incarnation are intended to enable developers to write code that interacts with the database in a highly productive manner. While the increased productivity of database controls is a boon, developers should understand that they provide considerably less flexibility than an equivalent EJB. They are particularly well suited for supporting smaller applications and discrete pieces of functionality where the large feature set and complexity of EJBs is not required. In these cases the increased productivity of the database control is the compelling argument for their usage.

However, there are certainly cases where the power and flexibility of EJB is needed and database controls should not be used. Specifically, database controls may be less than optimal in applications whose components require complex transaction management or declarative transactions. These applications should strongly consider using an EJB architecture instead of database controls as database controls provide limited flexibility with respect to transaction management.

Second, with respect to object persistence, larger applications that feature a highly complex domain model with many relationships between data elements and are evaluating database controls for CRUD operations should consider choosing a more robust and flexible persistence mechanism such as entity beans, Hibernate, or Toplink. This is because the database control provides no mechanism for transparently managing relationships between objects and developers can quickly find themselves overwhelmed in writing this glue code in complex situations.

Best Practice: Carefully consider the requirements for your particular needs prior to choosing a technological architecture; database controls are not a panacea for every situation.

Database Control Encapsulation
Our first task is to decide on the organization of code for our polling portlet. It is here that many developers using the database control make their first mistake - a mistake they sometimes do not realize until much later in the development cycle.

The problem arises from the fact that unlike many of the controls in WebLogic Workshop, a database control is a Java interface, not a class. When the control is compiled, the WebLogic Workshop framework creates an implementing class based on the attributes and methods defined by the developer in the database control interface. The sample method below retrieves an instance of the Question class based on an identifier.


    /**
     * @jc:sql statement::
     *     SELECT QUESTION_ID ID,TEXT
     *     FROM QUESTION
     *     WHERE QUESTION_ID={questionId}
     * ::
     */
    Question getQuestion(long questionId) throws SQLException;

Often a developer who is new to database controls will initially start with a simple control that performs basic CRUD operations. The developer will then start using this database control in page flows and processes as needed. At some point though, the developer will realize that he needs to perform a complex operation that cannot be encapsulated in a single method call. This is a problem we will also face in our polling portlet in many instances, for example deleting a question also requires us to delete all of the answers and responses.

Since the database control is defined as an interface, there is no opportunity for the developer to add custom code to the database control itself. Now the developer is forced to add two or more methods and rely on the user of the database control to call those methods in the correct order. For example, to delete a question we would need to have three database control methods, one to delete the question, one to delete the question's answers, and one to delete the question's responses.

When the presentation layer has to delete a question, it is clearly undesirable to force the presentation to call these three methods individually in the correct order. Further complicating the issue is that the presentation layer would have to call these methods within the context of a transaction in order to ensure the deletion is rolled back should the second or third method calls on the database control fail.

A far better approach is to encapsulate the database control within a Java custom control. In this way we never expose the database control directly to consumers such as page flows and processes; they will use the Java custom control instead. Thus these consumers are completely oblivious to the fact that database controls are being used as the implementation mechanism; all they perceive is the encapsulating Java custom control.

This approach has two primary benefits:

  • Increased maintainability: The control developer can expose methods on the database control directly through encapsulation. If these methods require additional logic or that operations be added later in the development life cycle, the control developer can expand the functionality as needed in the Java custom control without negatively impacting code that is using the control. If the database control were exposed directly, this would not be possible.

    An additional maintenance benefit is that if the underlying database control needs to be replaced with a more robust mechanism such as an EJB, this can be done without necessarily needing to modify code external to the encapsulating custom control.

  • Reduced transaction complexity: Each call to a control method starts a transaction if one has not already been started. Thus a call to two database control methods will happen as two transactions unless another transaction, such as a UserTransaction, has already been started. If the two database control calls were placed in a single Java custom control method, the transaction would automatically be started by the call to the custom control and the two database control methods would happen in the context of a single transaction as desired, with no additional code being written by the developer.

    Best Practice: Always encapsulate a database control within a Java custom control and avoid using database controls directly in page flows and processes.

    Now that we have established the importance of encapsulating the database control within a Java custom control, the next area of discussion is organizing your controls with an appropriate package hierarchy. Given that controls are compiled into Java classes, I highly recommend that you utilize standard Java naming conventions for packages. In WebLogic Workshop, this means creating folders for each level of the package hierarchy. In our particular use case, we will place our code and controls within the package com.musicsearch.poller. The implementing Java custom control we will use will be called PollerImpl.

    Figure 3 shows our PollerImpl control with the embedded database control PollerDBControl.

    Best Practice: Use standard Java naming conventions for packages when creating folders for containing controls.

    Next we have to determine where to place the database control that we will use for working with the underlying tables. It is important to convey to developers that the database control is an implementation-specific class not meant for public consumption. Many organizations have a naming convention in place for identifying packages that contain implementatio- specific classes and these packages are often named internal or impl.

    In our example we will place the database control within a subpackage called impl. The package structure used in building our control project to support the portlet is shown in Figure 4.

    Best Practice: Place database controls within an implementation package to clearly indicate it is an implementation specific artifact.

    Object Persistence and Database Controls
    In order for the portlet to display a question and answer to the user we need to add appropriate methods to the database control to load the Question and Answer objects from a select statement. This is done quite easily, as illustrated in the code sample below.

    
        /**
         * @jc:sql statement::
         *     SELECT ANSWER_ID ID, QUESTION_ID QUESTIONID, TEXT
         *     FROM ANSWER
         *     WHERE ANSWER_ID={questionId}
         * ::
         */
        Answer[] getAnswers(long questionId) throws SQLException;
    

    BEA documentation in WebLogic 8.1 GA and SP2 implies that your member fields must be public in order for the objects to be able to interact with a database control. This is in fact incorrect; you should create your value objects in accordance with standard Java practices, namely private fields with public method accessors, i.e., getters and setters.

    Therefore, instead of declaring the Answer class with public fields as follows:

    
    public class Answer
    {
        public long id = -1;
        public String text;
    }
    

    we declare it as per standard Java conventions using private fields and public method accessors:

    
    public class Answer
    {
        private long id = -1;
        private String text;
    
        public long getId()
        {
            return id;
        }
    
        public void setId(long value)
        {
            this.id = value;
        }
    
        public String getText()
        {
            return text;
        }
    
        public void setText(String value)
        {
            text = value;
        }
    }
    

    Best Practice: Create classes for use with database controls in accordance with standard Java practices and conventions.

    Another issue that often arises is naming conventions for class members. In order to load an object with values from a select statement, the database control requires that the member names be identical to column names in the database. Given that naming conventions for database columns and Java members vary considerably, this requirement could potentially result in poor names in either the database or Java class scope.

    Fortunately, an easy way to resolve the issue is to simply alias the columns as needed within the select statement in the database control so that column aliases conform to the correct member names. In the example below, we alias the column QUESTION_ID to ID in order for the database control to apply the column value to the Id member without mangling names of either the database column or the Java class member.

    
        /**
         * @jc:sql statement::
         *     SELECT QUESTION_ID ID,TEXT
         *     FROM QUESTION
         *     WHERE QUESTION_ID={questionId}
         * ::
         */
        Question getQuestion(long questionId) throws SQLException;
    

    Best Practice: Avoid mangling member names by aliasing Database columns in queries to match the member name as required.

    Conclusion
    This article demonstrated a variety of best practices with respect to the database control in the context of a polling portlet. Using these techniques will enable you to avoid potential pitfalls with database controls during the development life cycle.

  • More Stories By Gerald Nunn

    Gerald Nunn works as a Principal Consultant at BEA Systems assisting clients to implement solutions on the Weblogic Platform. Prior to joining BEA Systems, Gerald was the Director of Java Development at Workbrain.

    Comments (1) View Comments

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


    Most Recent Comments
    Sravan reddy 01/20/05 04:35:37 AM EST

    The article was very useful.I would like to know if we can run a query spanning multiple databses using db controls?

    eg say we have Emp table in database Sample1 and dept table in Sample2 database.

    @ThingsExpo Stories
    In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
    In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
    Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
    With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
    Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
    The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
    No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
    Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
    DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
    @DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
    Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
    SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
    SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
    SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
    SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
    SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
    SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
    SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...