4.1. Pojo Classes

About the author

Sandra L Sandra is the best. Toevoegen: iets over Sandra en over wat maakt dat ze plezier heeft in haar werk.

In this first blog, we will start with the creation of Java POJO classes which represent data from a database. We will create a so-called code instruction, which in combination with a data model will form the basis of generating code. We will also explain how functions can be used to apply a consistent naming of classes, fields, and methods for example. Finally, we will be adding methods to our classes.

4.1.1. Data model

The data model which we will use in this article looks like this:

../_images/M13_DataModel.png

Fig. 4.1 Data model

Listing 4.1 Model object
1<!--I need to be here.
2    But I am not yet -->

Let’s start with creating a very simple class for the entity Book:

Listing 4.2 class Book
 1package org.blog1.pojo;
 2
 3public class Book {
 4
 5private String name;
 6private String description;
 7private Author author;
 8
 9// Getters and setters
10
11}

There are quite some similarities between the data model and the entity for Book. We take advantage of these similarities to create ‘code instructions’, which will contain the blueprint for, in our case, Java classes. As all POJO classes have a similar structure, it is very convenient to use these code instructions to create more classes.

4.1.2. Code instruction

For our POJO classes we can define the following code instruction using XML:

Listing 4.3 Code instruction
 1<java_package
 2    xmlns="https://metafactory.io/xsd/v1/java-codeinstruction"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="https://metafactory.io/xsd/v1/java-codeinstruction
 5                              https://metafactory.io/xsd/v1/java-codeinstruction.xsd"
 6    name="org.blog1.pojo"
 7    package="domain_model">
 8
 9    <class name="${object.name}"
10           visibility="public"
11           foreach="object">
12
13        <field name="${attribute.name}"
14               visibility="private"
15               foreach="attribute">
16            <datatype>${attribute.type}</datatype>
17        </field>
18
19        <field name="${reference.name}"
20               visibility="private"
21               foreach="reference">
22            <datatype>${reference.type}</datatype>
23        </field>
24    </class>
25</java_package>

This is a good example of using Metaprogramming to describe POJO’s. Let’s first have a look at how a class is defined (from line 9 on):

name=”${object.name}”

This property describes the access modifier, in this case, of the class.

visibility=”public”

This property describes the access modifier, in this case, of the class.

foreach=”object”

The property defines in this case that we want to generate a class for every object defined in our data model.

This really emphasizes the advantages of a tool like MetaFactory’s Code Composer. Instead of having to write similar POJO classes for every entity by hand, you can now generate classes like these for all objects in the data model. You only need to define the desired objects.

Next we have two different types of fields defined in our code instruction: one based on the attributes and one based on the references in our data model. Our model object Book (see Model object) for example contains two attributes: name and description. For each of these attributes we want to generate a field with a private access modifier. The name of the field will now be based on the name of the attribute in our data model (i.e. description). The child element datatype in our code instruction describes the type of the Java field, based on the type of the attribute in the data model (i.e. String). The second type of field is based on the references and follows the same logic as for the attributes.

Now we can use this code instruction to generate, with one mouse click, both the Book and Author classes by means of the Code Composer.

The Author class should look like this:

Listing 4.4 class Author
1package org.blog1.pojo;
2
3public class Author {
4
5private String firstName;
6private String lastName;
7private Book book;
8
9}

The fields firstName and lastName are based on the 2 attributes of the Author model object and the field book is created based on the reference of Author to Book in the Author object.

4.1.3. Functions

Naming is an important aspect of Metaprogramming. In Listing 4.3 (line 9) we used the name of the model object for naming our Java POJO class. In this case that might be sufficient, but there are plenty of other situations where you might want to apply more advanced naming conventions. In MetaFactory we therefore have something called “code instruction functions”. These functions can be used in code instructions to describe all kinds of properties. Let’s have a look again at the names of the POJO classes and try to replace those with a function:

Listing 4.5 Function to create a class name
 1(...)
 2
 3<function name="createPojoClassName">
 4    <!-- Function must be called with 1 argument: 1. Name of model object -->
 5
 6    <definition>${arg1}</definition>
 7
 8</function>
 9
10(...)

Applying this function to our code instruction, it will look like this:

Listing 4.6 Code instruction
 1<java_package
 2    xmlns="https://metafactory.io/xsd/v1/java-codeinstruction"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="https://metafactory.io/xsd/v1/java-codeinstruction
 5                              https://metafactory.io/xsd/v1/java-codeinstruction.xsd"
 6    name="org.blog1.pojo"
 7    package="domain_model">
 8
 9    <class name=="${createPojoClassName(${object.name})}"
10           visibility="public"
11           foreach="object">
12
13        <field name="${attribute.name}"
14               visibility="private"
15               foreach="attribute">
16            <datatype>${attribute.type}</datatype>
17        </field>
18
19        <field name="${reference.name}"
20               visibility="private"
21               foreach="reference">
22            <datatype>${createPojoClassName(${reference.type})}
23            </datatype>
24        </field>
25    </class>
26</java_package>

We have first used this function to determine the class name and currently it will have the same result as in Listing 4.1. One major advantage of this solution is that if we want to change the names of our POJO classes, for example to BookEntity and AuthorEntity, we only have to adjust this one function and give the Code Composer a kick again.

All classes created based on this code instruction will be updated with this new naming convention. Even better, also the type of our reference fields will automatically be adjusted. This is just a very simple example, but hopefully you recognize how convenient these functions are. They will result in consistent naming and are less error prone than changing all names manually.

4.1.4. Methods

Our Java POJOs can use some getter and setter methods for access to the private fields. You need only a small adjustment to the code instruction to generate getters and setters:

Listing 4.7 Introducing Getters and Setters
 1<java_package
 2    xmlns="https://metafactory.io/xsd/v1/java-codeinstruction"
 3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="https://metafactory.io/xsd/v1/java-codeinstruction
 5                              https://metafactory.io/xsd/v1/java-codeinstruction.xsd"
 6    name="org.blog1.pojo"
 7    package="domain_model">
 8
 9    <class name=="${createPojoClassName(${object.name})}"
10           visibility="public"
11           foreach="object">
12
13        <field name="${attribute.name}"
14               visibility="private"
15               access="RW"
16               foreach="attribute">
17            <datatype>${attribute.type}</datatype>
18        </field>
19
20        <field name="${reference.name}"
21               visibility="private"
22               access="RW"
23               foreach="reference">
24            <datatype>${createPojoClassName(${reference.type})}
25            </datatype>
26        </field>
27    </class>
28</java_package>

By adding the access property with value r (read), w (write), or rw, we can indicate whether we want getter and/or setter methods to be generated. To really complete the POJO classes we can also add implementations for equals and hashCode methods.

Let’s further expand the code instruction and add these methods:

Listing 4.8 equals and hashCode methods
 1<method name=”equals”
 2        visibility=”public”>
 3    <annotation>@Override</annotation>
 4
 5    <parameter name=”return”>
 6        <apicommentline>Return true if object is the same as the argument object,
 7                        otherwise return false</apicommentline>
 8        <datatype>boolean</datatype>
 9    </parameter>
10
11    <parameter name=”other”>
12        <apicommentline>The reference object with which to compare</apicommentline>
13        <datatype>Object</datatype>
14    </parameter>
15
16    <body>${fmsnippet.java.pojo.method.equals}</body>
17</method>
18
19<method name=”hashCode”
20        visibility=”public”>
21    <annotation>@Override</annotation>
22
23    <parameter name=”return”>
24        <apicommentline>A hash code value for this object</apicommentline>
25        <datatype>integer</datatype>
26    </parameter>
27
28    <body>${fmsnippet.java.pojo.method.hash_code}</body>
29</method>

Lines 16 and 28 tell the Code Composer to call Freemarker snippets for the generation of the methods’ body.

The Code Composer will then generate these 2 classes:

Listing 4.9 class Book
  1package org.blog1.pojo;
  2
  3import java.util.Objects;
  4
  5public class Book {
  6
  7        private String name;
  8
  9        private String description;
 10
 11        private Author author;
 12
 13        /**
 14        * equals – Fields used as business key: 1) name 2) description.
 15        *
 16        * @param other The reference object with which to compare
 17        * @return boolean Return true if object is the same as the argument
 18          object, otherwise return false
 19        */
 20        @Override
 21        Public Boolean equals(final Object other) {
 22                if (this == other) {
 23                        return true;
 24                }
 25
 26                if (!(other instanceof Book)) {
 27                        return false;
 28                }
 29
 30                final Book otherBook = (Book) other;
 31
 32                boolean result;
 33                result = Objects.equals(getName(), otherBook.getName());
 34                result = result && Objects.equals(getDescription(),
 35                        otherBook.getDescription());
 36
 37                return result;
 38        }
 39
 40        /**
 41        * hashCode – Fields used as business key: 1) name 2) description.
 42        *
 43        * @return integer A hash code value for this object
 44        */
 45        @Override
 46        Public int hashCode() {
 47                Return Objects.hash(getName(), getDescription());
 48        }
 49
 50        /**
 51        * Getter for property name.
 52        *
 53        * @return Value of property name
 54        */
 55        public String getName() {
 56                return this.name;
 57        }
 58
 59        /**
 60        * Setter for property name.
 61        *
 62        * @param name New value of property name
 63        */
 64        public void setName(final String name) {
 65                this.name = name;
 66        }
 67
 68        /**
 69        * Getter for property description.
 70        *
 71        * @return Value of property description
 72        */
 73        public String getDescription() {
 74                return this.description;
 75        }
 76
 77        /**
 78        * Setter for property description.
 79        *
 80        * @param name New value of property description
 81        */
 82        public void setDescription(final String description) {
 83                this.description = description;
 84        }
 85
 86        /**
 87        * Getter for property author.
 88        *
 89        * @return Value of property author
 90        */
 91        public Author getAuthor() {
 92                return this.author;
 93        }
 94
 95        /**
 96        * Setter for property author.
 97        *
 98        * @param author New value of property author
 99        */
100        public void setAuthor(final Author author) {
101                this.author = author;
102        }
103}
Listing 4.10 class Author
  1package org.blog1.pojo;
  2
  3import java.util.Objects;
  4
  5public class Author {
  6
  7        private String firstName;
  8
  9        private String lastName;
 10
 11        private Book book;
 12
 13        /**
 14        * equals – Fields used as business key: 1) firstName 2) lastName.
 15        *
 16        * @param other The reference object with which to compare
 17        * @return boolean Return true if object is the same as the argument
 18          object, otherwise return false
 19        */
 20        @Override
 21        Public Boolean equals(final Object other) {
 22                if (this == other) {
 23                        return true;
 24                }
 25
 26                if (!(other instanceof Author)) {
 27                        return false;
 28                }
 29
 30                final Author otherAuthor = (Author) other;
 31
 32                boolean result;
 33                result = Objects.equals(getFirstName(), otherAuthor.getFirstName());
 34                result = result && Objects.equals(getLastName(), otherAuthor.getLastName());
 35
 36                return result;
 37        }
 38
 39        /**
 40        * hashCode – Fields used as business key: 1) firstName 2) lastName.
 41        *
 42        * @return integer A hash code value for this object
 43        */
 44        @Override
 45        Public int hashCode() {
 46                Return Objects.hash(getFirstName(), getLastName());
 47        }
 48
 49        /**
 50        * Getter for property firstName.
 51        *
 52        * @return Value of property firstName
 53        */
 54        public String getFirstName() {
 55                return this.firstName;
 56        }
 57
 58        /**
 59        * Setter for property firstName.
 60        *
 61        * @param firstName New value of property firstName
 62        */
 63        public void setFirstName(final String firstname) {
 64                this.firstName = firstName;
 65        }
 66
 67        /**
 68        * Getter for property lastName.
 69        *
 70        * @return Value of property lastName
 71        */
 72        public String getLastName() {
 73                return this.lastName;
 74        }
 75
 76        /**
 77        * Setter for property lastName.
 78        *
 79        * @param lastName New value of property lastName
 80        */
 81        public void setLastName(final String lastName) {
 82                this.lastName = lastName;
 83        }
 84
 85        /**
 86        * Getter for property book.
 87        *
 88        * @return Value of property book
 89        */
 90        public Book getBook() {
 91                return this.book;
 92        }
 93
 94        /**
 95        * Setter for property book.
 96        *
 97        * @param book New value of property book
 98        */
 99        public void setBook(final Book book) {
100                this.book = book;
101        }
102
103}

In the next blog of this series, we’ll explain how you can use the Freemarker template engine in various ways.