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::
     *     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::
         *     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::
         *     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.

    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.

    IoT & Smart Cities Stories
    Contextual Analytics of various threat data provides a deeper understanding of a given threat and enables identification of unknown threat vectors. In his session at @ThingsExpo, David Dufour, Head of Security Architecture, IoT, Webroot, Inc., discussed how through the use of Big Data analytics and deep data correlation across different threat types, it is possible to gain a better understanding of where, how and to what level of danger a malicious actor poses to an organization, and to determin...
    The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
    The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
    We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
    Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
    As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
    Machine learning has taken residence at our cities' cores and now we can finally have "smart cities." Cities are a collection of buildings made to provide the structure and safety necessary for people to function, create and survive. Buildings are a pool of ever-changing performance data from large automated systems such as heating and cooling to the people that live and work within them. Through machine learning, buildings can optimize performance, reduce costs, and improve occupant comfort by ...
    René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
    With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
    Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.