Create a simple relationship between entities by creating two entity classes with a relationship, registering the entities with the ObjectGrid, and storing the entity instances into the cache.
Customer.java @Entity public class Customer { @Id String id; String firstName; String surname; String address; String phoneNumber; }This class includes information about the customer such as name, address, and phone number.
Order.java @Entity public class Order { @Id String orderNumber; Date date; @ManyToOne(cascade=CascadeType.PERSIST) Customer customer; String itemName; int quantity; double price; }In this example, a reference to a Customer object replaces the customerName attribute. The reference has an annotation that indicates a many-to-one relationship. A many-to-one relationship indicates that each order has one customer, but multiple orders might reference the same customer. The cascade annotation modifier indicates that if the EntityManager persists the Order object, it must also persist the Customer object. If you choose to not set the cascade persist option, which is the default option, you must manually persist the Customer object with the Order object.
Application.java public class Application { static public void main(String [] args) throws Exception { ObjectGrid og = ObjectGridManagerFactory.getObjectGridManager().createObjectGrid(); og.registerEntities(new Class[] {Order.class}); Session s = og.getSession(); EntityManager em = s.getEntityManager(); em.getTransaction().begin(); Customer cust = new Customer(); cust.address = "Main Street"; cust.firstName = "John"; cust.surname = "Smith"; cust.id = "C001"; cust.phoneNumber = "5555551212"; Order o = new Order(); o.customer = cust; o.date = new java.util.Date(); o.itemName = "Widget"; o.orderNumber = "1"; o.price = 99.99; o.quantity = 1; em.persist(o); em.getTransaction().commit(); em.getTransaction().begin(); o = (Order)em.find(Order.class, "1"); System.out.println("Found order for customer: " + o.customer.firstName + " " + o.customer.surname); em.getTransaction().commit(); } }This application is similar to the example application that is in the previous step. In the preceding example, only a single class Order is registered. WebSphere® eXtreme Scale detects and automatically includes the reference to the Customer entity, and a Customer instance for John Smith is created and referenced from the new Order object. As a result, the new customer is automatically persisted, because the relationship between two orders includes the cascade modifier, which requires that each object be persisted. When the Order object is found, the entity manager automatically finds the associated Customer object and inserts a reference to the object.