Combined Entity Pattern
The Composite Entity Pattern is used in the EJB persistence mechanism. A composite entity is an EJB entity bean that represents a representation of an object. When a composite entity is updated, the internal dependent object beans are automatically updated because they are managed by the EJB entity beans. The following are the participants of the composite entity bean.
Composite Entity - It is the main entity bean. It can be coarse-grained, or it can contain a coarse-grained object for persistent lifetime.
Coarse-Grained Object - This object contains previous objects. It has its own life cycle and can also manage the life cycle of dependent objects.
Dependent Object (Dependent Object) - A dependent object is an object whose continuous life cycle depends on a coarse-grained object.
Strategies - Strategies represent how to implement composite entities.
Implementation
We will create a CompositeEntity object that is a composite entity. CoarseGrainedObject is a class containing dependent objects.
CompositeEntityPatternDemo, our demo class uses the Client class to demonstrate the usage of the composite entity pattern.
Step 1
Create dependent objects.
DependentObject1.java
public class DependentObject1 { private String data; public void setData(String data){ this.data = data; } public String getData(){ return data; } }
DependentObject2.java
public class DependentObject2 { private String data; public void setData(String data){ this.data = data; } public String getData(){ return data; } }
Step 2
Create coarse-grained objects .
CoarseGrainedObject.java
public class CoarseGrainedObject { DependentObject1 do1 = new DependentObject1(); DependentObject2 do2 = new DependentObject2(); public void setData(String data1, String data2){ do1.setData(data1); do2.setData(data2); } public String[] getData(){ return new String[] {do1.getData(),do2.getData()}; } }
Step 3
Create a composite entity.
CompositeEntity.java
public class CompositeEntity { private CoarseGrainedObject cgo = new CoarseGrainedObject(); public void setData(String data1, String data2){ cgo.setData(data1, data2); } public String[] getData(){ return cgo.getData(); } }
Step 4
Create a client class that uses composite entities.
Client.java
public class Client { private CompositeEntity compositeEntity = new CompositeEntity(); public void printData(){ for (int i = 0; i < compositeEntity.getData().length; i++) { System.out.println("Data: " + compositeEntity.getData()[i]); } } public void setData(String data1, String data2){ compositeEntity.setData(data1, data2); } }
Step 5
Use Client to demonstrate the use of the combined entity design pattern.
CompositeEntityPatternDemo.java
public class CompositeEntityPatternDemo { public static void main(String[] args) { Client client = new Client(); client.setData("Test", "Data"); client.printData(); client.setData("Second Test", "Data1"); client.printData(); } }
Step 6
Verify the output.
Data: Test Data: Data Data: Second Test Data: Data1