A common relationship between classes is composition. One class may declare and use another class as a field to support some common functionality. For example, the PartsBean
may have a need to maintain the location of the part using some sort of bin location scheme. This scheme may also be used for classes other than a part. This need is addressed for entities using the @Embeddable and @Embedded annotations.
The steps to embed a class within another class involves:
We will expand upon the previous recipe and augment the EntityBeanApplication
application.
The @Embeddable annotation is used to declare a class which can be embedded within another class. Add the BinLocation
class to the EntityBeanApplication
application as part of the packt
package. This class possesses aisle
and level
fields to specify the location of an item. Add get and set methods for these fields.
@Embeddable public class BinLocation implements Serializable { private int aisle; private int level; public int getAisle() { return aisle; } public void setAisle(int aisle) { this.aisle = aisle; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } }
The next step is to embed the BinLocation
class into the PartsBean
. The @Embedded annotation designates a class as one which will be included in the class. Modify the PartsBean
class by adding a reference variable to this class using the @Embedded annotation.
@Embedded BinLocation binLocation;
Add get and set methods to allow modification of the bin location. We could have also added individual methods for the aisle and level.
public BinLocation getBinLocation() { return binLocation; } public void setBinLocation(BinLocation binLocation) { this.binLocation = binLocation; }
Modify the PartsServlet
to create and use a new BinLocation
object as follows:
parts = new PartsBean(); ... BinLocation binLocation = new BinLocation(); binLocation.setAisle(12); binLocation.setLevel(3); parts.setBinLocation(binLocation); partsFacade.create(parts);
The BinLocation
class is simple. In order to use it in the PartsBean
we used the @Embedded annotation. However, to make this object available to users of PartsBean
we had to add the getBinLocation
and setBinLocation
methods to the entity. In the PartsServlet
, we created a new BinLocation
object and set aisle and level values for a part. The setBinLocation
method was used to associate the BinLocation
object with the PartsBean
instance.
18.118.7.102