April 26, 2011, 11:54 a.m.
posted by hashspark
Exercise 6.4: Multitable MappingsThis exercise demonstrates how you can use the @javax.persistence.SecondaryTable annotation to map one entity class to multiple tables. Start Up JBossIf you already have JBoss running, there is no reason to restart it. Otherwise, start it up as instructed in Workbook 1. Initialize the DatabaseThe database tables will be created when Exercise 6.4 is deployed to JBoss. If you have problems running this example, shut down JBoss and run the clean.db Ant task. Build and Deploy the Example ProgramsPerform the following steps:
As in the last exercise, titan.jar is rebuilt, copied to the JBoss deploy directory, and redeployed by the application server. Examine the Customer EntityThe Customer entity is mapped to two different tables: CUSTOMER_TABLE and ADDRESS_TABLE . The firstName and lastName properties are stored in CUSTOMER_TABLE, and the street, address, and city properties are stored in ADDRESS_TABLE. Customer.java
package com.titan.domain;
import javax.persistence.*;
package com.titan.domain;
import javax.persistence.*;
@Entity
@Table(name="CUSTOMER_TABLE")
@SecondaryTable(name="ADDRESS_TABLE",
pkJoinColumns={
@PrimaryKeyJoinColumn(name="ADDRESS_ID")})
public class Customer implements java.io.Serializable {
private long id;
private String firstName;
private String lastName;
private String street;
private String city;
private String state;
@Id @GeneratedValue
public int getId( ) { return id; }
public void setId(int id) { this.id = id; }
public String getFirstName( ) { return firstName; }
public void setFirstName(String first) { this.firstName = first; }
public String getLastName( ) { return lastName; }
public void setLastName(String last) { this.lastName = last; }
@Column(name="STREET", table="ADDRESS_TABLE")
public String getStreet( ) { return street; }
public void setStreet(String street) { this.street = street; }
@Column(name="CITY", table="ADDRESS_TABLE")
public String getCity( ) { return city; }
public void setCity(String city) { this.city = city; }
@Column(name="STATE", table="ADDRESS_TABLE")
public String getState( ) { return state; }
public void setState(String state) { this.state = state; }
}
Examine Other FilestravelAgentBean again acts as a simple data access object, wrapping invocations around the EntityManager instance injected into this EJB. The Client application simply allocates a Customer entity and then calls createCustomer( ) and findCustomer( ) to insert and find the Customer in the database. Because they are so simple and similar to other exercises in this chapter, we won't go over them in detail. Run the ClientRun the Client application by invoking ant run.client at the command prompt. Remember to set your JBOSS_HOME and PATH environment variables. This is the output:
run.client:
[java] Bill
[java] Burke
[java] Clarendon Street
[java] Boston
[java] MA
|
- Comment