March 7, 2009, 10:46 p.m.
posted by hashspark
Exercise 6.3: @EmbeddedIdThis exercise shows you an example of using @javax.persistence.EmbeddedId to map a primary key class to the database. It also shows how the @javax.persistence.Transient annotation can be used to mark nonpersistent properties. Start Up JBossIf you already have JBoss running, there is no reason to restart it. Otherwise, start it up as instructed Workbook 1. Initialize the DatabaseThe database tables will be created when Exercise 6.3 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 in this exercise is pretty close to the @EmbeddedId example in Chapter 6, except that an example of @TRansient properties was added to illustrate this concept. Customer.java
public class Customer implements java.io.Serializable {
private String firstName;
private CustomerPK
pk;
public String getFirstName( ) { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name="lastName", column=@Column(name="LAST_NAME"),
@AttributeOverride(name="ssn", column=@Column(name="SSN"))
})
public PK getPk( ) { return pk; }
public void setPk(CustomerPK pk) { this.pk = pk; }
@Transient
public String getLastName() { return pk.getLastName( ); }
@Transient
public long getSsn() { return pk.getSsn( ); }
}
The getLastName( ) and getSsn( ) methods are marked as @TRansient because they are not persistent properties. They are simply convenience methods for accessing the lastName and ssn properties stored in the CustomerPK primary key class. 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] 9999999
|
- Comment