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 3: Lazy Initialization
Shows the effects of lazy initialization when an entity becomes detached from a persistence context.
Client.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
| package com.titan.clients;
import com.titan.access.*;
import com.titan.domain.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import java.util.List;
public class Client {
public static void main(String[] args) {
try {
Context jndiContext = getInitialContext();
Object ref = jndiContext.lookup("TitanCruises/DataAccessBean/remote");
DataAccess dao = (DataAccess) ref;
System.out.println("Fetch reservations with loaded relationships");
System.out.println();
List list = dao.fetchReservationsWithRelationships();
for (Object obj : list) {
Reservation res = (Reservation) obj;
System.out.println("Reservation for: "
+ res.getCruise().getName());
System.out.println("\tNum cabins: " + res.getCabins().size());
System.out.println("\tNum customers: "
+ res.getCustomers().size());
}
System.out.println("----------");
System.out.println("Try to access uninitialized relationships");
System.out.println("----------");
list = dao.fetchReservations();
for (Object obj : list) {
Reservation res = (Reservation) obj;
System.out.println("Reservation for: "
+ res.getCruise().getName());
try {
System.out.println("\tNum cabins: "
+ res.getCabins().size());
System.out.println("\tNum customers: "
+ res.getCustomers().size());
} catch (org.hibernate.LazyInitializationException ex) {
System.out.println(ex.getMessage());
}
}
} catch (javax.naming.NamingException ne) {
ne.printStackTrace();
}
}
public static Context getInitialContext()
throws javax.naming.NamingException {
return new javax.naming.InitialContext();
}
} |
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;}
} |
Initializedb.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.clients;
import com.titan.access.*;
import com.titan.domain.*;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import java.util.List;
public class Initializedb {
public static void main(String[] args) {
try {
Context jndiContext = getInitialContext();
Object ref = jndiContext.lookup("TitanCruises/DataAccessBean/remote");
DataAccess dao = (DataAccess) ref;
System.out.println(dao.initializeDatabase());
} catch (javax.naming.NamingException ne) {
ne.printStackTrace();
}
}
public static Context getInitialContext()
throws javax.naming.NamingException {
return new javax.naming.InitialContext();
}
} |
DataAccess.java
1
2
3
4
5
6
7
8
9
10
11
| package com.titan.access;
import javax.ejb.Remote;
import java.util.List;
@Remote
public interface DataAccess {
String initializeDatabase();
public List fetchReservations();
public List fetchReservationsWithRelationships();
} |
DataAccessBean.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
| package com.titan.access;
import javax.persistence.*;
import javax.ejb.*;
import java.io.*;
import com.titan.domain.*;
import java.util.List;
import java.util.Date;
@Stateless
public class DataAccessBean implements DataAccess {
@PersistenceContext(unitName = "titan")
EntityManager manager;
public List fetchReservations() {
return manager.createQuery("FROM Reservation res").getResultList();
}
public List fetchReservationsWithRelationships() {
List list = manager.createQuery("FROM Reservation res").getResultList();
for (Object obj : list) {
Reservation res = (Reservation) obj;
res.getCabins().size();
res.getCustomers().size();
}
return list;
}
public String initializeDatabase() {
List list = manager.createQuery("FROM Reservation res").getResultList();
if (list.size() > 0) {
return "Database already initialized with entities";
}
String output = null;
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
Customer bill = new Customer();
bill.setFirstName("Bill");
bill.setLastName("Burke");
bill.setHasGoodCredit(true);
Customer sacha = new Customer();
sacha.setFirstName("Sacha");
sacha.setLastName("Labourey");
sacha.setHasGoodCredit(false); // Sacha get's bad credit ;)
Customer marc = new Customer();
marc.setFirstName("Marc");
marc.setLastName("Fleury");
marc.setHasGoodCredit(true);
Address addr = new Address();
addr.setStreet("123 Boston Road");
addr.setCity("Billerica");
addr.setState("MA");
addr.setZip("01821");
bill.setAddress(addr);
addr = new Address();
addr.setStreet("Etwa Schweitzer Strasse");
addr.setCity("Neuchatel");
addr.setState("Switzerland");
addr.setZip("07711");
sacha.setAddress(addr);
addr = new Address();
addr.setStreet("JBoss Dr.");
addr.setState("Atlanta");
addr.setCity("GA");
addr.setZip("06660");
marc.setAddress(addr);
CreditCard cc;
cc = new CreditCard();
cc.setExpirationDate(new Date());
cc.setNumber("5324 9393 1010 2929");
cc.setNameOnCard("Bill Burke");
cc.setCreditOrganization("Capital One");
bill.setCreditCard(cc);
cc = new CreditCard();
cc.setExpirationDate(new Date());
cc.setNumber("3311 5000 1011 2333");
cc.setNameOnCard("Sacha Labourey");
cc.setCreditOrganization("American Express");
sacha.setCreditCard(cc);
cc = new CreditCard();
cc. |