Using embeddable classes in entities

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.

Getting ready

The steps to embed a class within another class involves:

  1. Designating the class that can be embedded with the @Embeddable annotation
  2. Embedding the embeddable class into the other class using the @Embedded annotation

    We will expand upon the previous recipe and augment the EntityBeanApplication application.

How to do it...

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);

How it works...

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.

See also

The Using the EntityManager recipe illustrates the complete process to persist a PartsBean.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.9.148