EJB3: Entity Relationships Example 2

by admin ~ October 21, 2008

Following are the examples from the chapter “Entity Relationships” from the book “Enterprise JavaBeans 3.0″ by Bill Bruke & Richard Monson-Haefel. This example I have tried it out on JBoss AS 5.0.0.CR1. I have used Postgresql as the database. And I have used eclipse WTP as IDE.


Example 2: Inverse Relationship

This example is showing what happens when only inverse side of a relationship is modified.


Client.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.titan.clients;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import com.titan.domain.*;
import com.titan.travelagent.TravelAgentRemote;
 
public class Client {
	public static void main(String[] args) throws Exception {
		try {	
			Context jndiContext = new InitialContext();
			Object ref = jndiContext
					.lookup("TitanCruises/TravelAgentBean/remote");
			TravelAgentRemote dao = (TravelAgentRemote) ref;
			Customer cust = dao.createCustomerAddress();
			dao.createCreditCard(cust);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

jndi.properties

1
2
3
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=127.0.0.1:1099

Address.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.titan.domain;
 
import javax.persistence.*;
 
@Entity
public class Address implements java.io.Serializable {
	private int id;
	private String street;
	private String city;
	private String state;
	private String zip;
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public String getStreet() {return street;}
	public void setStreet(String street) {this.street = street;}
	public String getCity() {return city;}
	public void setCity(String city) {this.city = city;}
	public String getState() {return state;}
	public void setState(String state) {this.state = state;}
	public String getZip() {return zip;}
	public void setZip(String zip) {this.zip = zip;}
}

Cabin.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.titan.domain;
 
import javax.persistence.*;
 
@Entity
public class Cabin implements java.io.Serializable {
	private int id;
	private String name;
	private int bedCount;
	private int deckLevel;
	private Ship ship;
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public String getName() {return name;}
	public void setName(String name) {this.name = name;}
	public int getBedCount() {return bedCount;}
	public void setBedCount(int count) {this.bedCount = count;}
	public int getDeckLevel() {return deckLevel;}
	public void setDeckLevel(int level) {this.deckLevel = level;}
	@ManyToOne
	@JoinColumn(name = "SHIP_ID")
	public Ship getShip() {return ship;}
	public void setShip(Ship ship) {this.ship = ship;}
}

CreditCard.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.titan.domain;
 
import javax.persistence.*;
import java.util.Date;
 
@Entity
public class CreditCard implements java.io.Serializable {
	private int id;
	private Date expirationDate;
	private String number;
	private String nameOnCard;
	private String creditOrganization;
	private Customer customer;
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public Date getExpirationDate() {return expirationDate;}
	public void setExpirationDate(Date date) {expirationDate = date;}
	public String getNumber() {return number;}
	public void setNumber(String number) {this.number = number;}
	public String getNameOnCard() {return nameOnCard;}
	public void setNameOnCard(String name) {nameOnCard = name;}
	public String getCreditOrganization() {return creditOrganization;}
	public void setCreditOrganization(String org) {creditOrganization = org;}
	@OneToOne(mappedBy = "creditCard")
	public Customer getCustomer() {return customer;}
	public void setCustomer(Customer customer) {this.customer = customer;}
}

Cruise.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.titan.domain;
 
import java.util.*;
import javax.persistence.*;
 
@Entity
public class Cruise implements java.io.Serializable {
	private int id;
	private String name;
	private Ship ship;
 
	private Collection<Reservation> reservations = new ArrayList<Reservation>();
 
	public Cruise() {}
	public Cruise(String name, Ship ship) {
		this.name = name;
		this.ship = ship;
	}
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public String getName() {return name;}
	public void setName(String name) {this.name = name;}
	@ManyToOne
	public Ship getShip() {return ship;}
	public void setShip(Ship ship) {this.ship = ship;}
	@OneToMany(mappedBy = "cruise")
	public Collection<Reservation> getReservations() {return reservations;}
	public void setReservations(Collection<Reservation> res) {reservations = res;}
}

Customer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.titan.domain;
 
import javax.persistence.*;
import java.util.*;
 
@Entity
public class Customer implements java.io.Serializable {
	private int id;
	private String firstName;
	private String lastName;
	private boolean hasGoodCredit;
	private Address address;
	private Collection<Phone> phoneNumbers = new ArrayList<Phone>();
	private CreditCard creditCard;
	private Collection<Reservation> reservations = new ArrayList<Reservation>();
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public String getFirstName() {return firstName;}
	public void setFirstName(String firstName) {this.firstName = firstName;}
	public String getLastName() {return lastName;}
	public void setLastName(String lastName) {this.lastName = lastName;}
	public boolean getHasGoodCredit() {return hasGoodCredit;}
	public void setHasGoodCredit(boolean flag) {hasGoodCredit = flag;}
 
	@OneToOne(cascade = { CascadeType.ALL })
	@JoinColumn(name = "ADDRESS_ID")
	public Address getAddress() {return address;}
	public void setAddress(Address address) {this.address = address;}
 
	@OneToOne(cascade = { CascadeType.ALL })
	public CreditCard getCreditCard() {return creditCard;}
	public void setCreditCard(CreditCard card) {creditCard = card;}
 
	@OneToMany(cascade = { CascadeType.ALL })
	@JoinColumn(name = "CUSTOMER_ID")
	public Collection<Phone> getPhoneNumbers() {return phoneNumbers;}
	public void setPhoneNumbers(Collection<Phone> phones) {this.phoneNumbers = phones;}
 
	@ManyToMany(mappedBy = "customers")
	public Collection<Reservation> getReservations() {return reservations;}
	public void setReservations(Collection<Reservation> reservations) {this.reservations = reservations;}
}

Phone.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.titan.domain;
 
import javax.persistence.*;
 
@Entity
public class Phone implements java.io.Serializable {
	private int id;
	private String number;
	private byte type;
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public String getNumber() {return number;}
	public void setNumber(String number) {this.number = number;}
	public byte getType() {return type;}
	public void setType(byte type) {this.type = type;}
}

Reservation.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.titan.domain;
 
import javax.persistence.*;
import java.util.*;
 
@Entity
public class Reservation implements java.io.Serializable {
	private int id;
	private Date date;
	private double amountPaid;
	private Cruise cruise;
	private Set<Cabin> cabins = new HashSet<Cabin>();
	private Set<Customer> customers = new HashSet<Customer>();
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public Date getDate() {return date;}
	public void setDate(Date date) {this.date = date;}
	public double getAmountPaid() {return amountPaid;}
	public void setAmountPaid(double amount) {amountPaid = amount;}
 
	@ManyToOne
	@JoinColumn(name = "CRUISE_ID")
	public Cruise getCruise() {return cruise;}
	public void setCruise(Cruise cruise) {this.cruise = cruise;}
 
	@ManyToMany
	@JoinTable(name = "RESERVATION_CABIN", joinColumns = { @JoinColumn(name = "RESERVATION_ID") }, inverseJoinColumns = { @JoinColumn(name = "CABIN_ID") })
	public Set<Cabin> getCabins() {return cabins;}
	public void setCabins(Set<Cabin> cabins) {this.cabins = cabins;}
 
	@ManyToMany
	@JoinTable(name = "RESERVATION_CUSTOMER", joinColumns = { @JoinColumn(name = "RESERVATION_ID") }, inverseJoinColumns = { @JoinColumn(name = "CUSTOMER_ID") })
	public Set<Customer> getCustomers() {return customers;}
	public void setCustomers(Set<Customer> customers) {this.customers = customers;}
}

Ship.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.titan.domain;
 
import javax.persistence.*;
 
@Entity
public class Ship implements java.io.Serializable {
	private int id;
	private String name;
	private double tonnage;
 
	public Ship() {}
	public Ship(String name, double tonnage) {
		this.name = name;
		this.tonnage = tonnage;
	}
 
	@Id
	@GeneratedValue
	public int getId() {return id;}
	public void setId(int id) {this.id = id;}
	public String getName() {return name;}
	public void setName(String name) {this.name = name;}
	public double getTonnage() {return tonnage;}
	public void setTonnage(double tonnage) {this.tonnage = tonnage;}
}

TravelAgentRemote.java

1
2
3
4
5
6
7
8
9
10
package com.titan.travelagent;
 
import javax.ejb.Remote;
import com.titan.domain.Customer;
 
@Remote
public interface TravelAgentRemote {
	public Customer createCustomerAddress();
	public Customer createCreditCard(Customer cust);
}

TravelAgentBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.titan.travelagent;
 
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.titan.domain.Address;
import com.titan.domain.CreditCard;
import com.titan.domain.Customer;
 
@Stateless
public class TravelAgentBean implements TravelAgentRemote {
	@PersistenceContext(unitName = "titan")
	private EntityManager manager;
 
	public Customer createCustomerAddress() {
		System.out.println("Create 1st Customer");
		Customer cust = new Customer();
		cust.setFirstName("Bill");
		cust.setLastName("Burke");
		Address address = new Address();
		address.setStreet("Beacon Street");
		address.setCity("Boston");
		address.setState("MA");
		address.setZip("02115");
		cust.setAddress(address);
 
		try {
			manager.persist(cust);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out
				.println("Address was also persisted with auto-generated key: "
						+ address.getId());
		System.out
				.println("Return detached Customer instance: " + cust.getId());
		return cust;
	}
 
	public Customer createCreditCard(Customer cust) {
		CreditCard card = new CreditCard();
		card.setExpirationDate(new java.util.Date());
		card.setNumber("4444-4444-4444-4444");
		card.setNameOnCard("William Burke");
		card.setCreditOrganization("Capital One");
		card.setCustomer(cust);
 
		try {
			manager.persist(card);
			// Show that card.getCustomer() returns null
			//manager.clear();
			CreditCard cardCopy = manager.find(CreditCard.class, card.getId());
 
			if(cardCopy == null){
				System.out.println("null");
			}else {
				System.out.println("not null");
			}
			System.out.println("should be null: " + cardCopy.getCustomer().getFirstName());
			System.out.println("now set the owning side of the relationship");
			Customer custCopy = manager.find(Customer.class, cust.getId());
			custCopy.setCreditCard(cardCopy);
			//manager.clear();
			cardCopy = manager.find(CreditCard.class, card.getId());
			System.out.println("should be set now: "
					+ cardCopy.getCustomer().getFirstName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cust;
	}
}

persistence.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<persistence:persistence version="1.0" xmlns:persistence="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd ">
  <persistence:persistence-unit name="titan" transaction-type="JTA">
    <persistence:description>Chapter: 7</persistence:description>
    <persistence:jta-data-source>java:/TitanDB</persistence:jta-data-source>
    <persistence:properties>
    	<persistence:property name="hibernate.hbm2ddl.auto" value="create"/>
    </persistence:properties>
  </persistence:persistence-unit>
</persistence:persistence>

Data Source file : postgres-TitanDB-ds.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
    <jndi-name>TitanDB</jndi-name>
	<use-java-context>true</use-java-context>
    <connection-url>jdbc:postgresql://127.0.0.1:5432/ejb3db</connection-url>
    <driver-class>org.postgresql.Driver</driver-class>
    <user-name>ranjan</user-name>
    <password>ranjan</password>
      <metadata>
         <type-mapping>PostgreSQL 8.0</type-mapping>
      </metadata>
  </local-tx-datasource>
</datasources>

application.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC
	"-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
	"http://java.sun.com/dtd/application_1_3.dtd">
<application>
	<display-name>TitanCruisesExample</display-name>
	<module>
		<ejb>TravelAgentBean.jar</ejb>
	</module>
	<module>
		<ejb>EntitiesBean.jar</ejb>
	</module>
</application>

Building the application: build.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?xml version="1.0" encoding="UTF-8"?>
<project name="Packaging Generator" default="_packaging_generation_">
	<target name="_packaging_generation_" depends="TitanCruisesExample" />
	<target name="TitanCruisesExample" description="TitanCruises.ear" depends="TravelAgentBean">
		<jar destfile="TitanCruises.ear">
			<zipfileset dir="conf" prefix="META-INF">
				<include name="application.xml" />
			</zipfileset>
			<zipfileset dir="/home/ranjan/workspaceEJB3/TitanCruises7_2">
				<include name="TravelAgentBean.jar" />
				<include name="EntitiesBean.jar" />
			</zipfileset>
		</jar>
	</target>
	<target name="TravelAgentBean" description="TravelAgentBean.jar" depends="EntitiesBean">
		<jar destfile="TravelAgentBean.jar">
			<zipfileset dir="/home/ranjan/workspaceEJB3/TitanCruises7_2/bin/com/titan/travelagent" prefix="com/titan/travelagent"/>
		</jar>
	</target>
	<target name="EntitiesBean" description="EntitiesBean.jar" >
		<jar destfile="EntitiesBean.jar">
			<zipfileset dir="conf" prefix="META-INF">
				<include name="persistence.xml" />
			</zipfileset>
			<zipfileset dir="/home/ranjan/workspa