Вы находитесь на странице: 1из 17

EJB3

M. Joundi Khalid

IGA 2009/2010
Master 2/ Miage

Lab 2

EJB3: Mapping Persistent Objects

In this Lab we illustrate basic mapping types. You will see examples of:

Autogenerated primary keys @IdClass and @EmbeddedId primary key class mappings @Temporal, @Transient, @Lob , and @Enumerated mappings An entity class that maps to multiple tables An entity class that has an embedded class as a property

Step1 : Start Up GlassFish Step2 : Initialize the Database Step3: create your EJB project :

Select File->New Project (Ctrl+Shift+N). The New Project dialog box appears. Under Choose Project pane, select Java EE under Categories and Entreprise Application For the Project Name field, type in EJBTestMappingPersistentObject as project name.Click Next. For Server field, select GlassFish v2.1, for Java EE Version, select Java EE 5. Select Create Application Client Module Click Finish.

Step 4 : Add persistence.xml Configuration file . Part 1 : Testing Autogenerated primary keys, Using @Temporal, @Transient, @Lob , and @Enumerated mappings

Step 1: Add / Examine Customer1 Entity class and CustomerType class

kjoundi@yahoo.com

Page 1

EJB3
import java.io.File; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import javax.persistence.Temporal; @Entity @Table(name="CUSTOMER_TABLE") public class Customer1 implements Serializable { private Long id; private String lastName; private String firstName; private CustomerType customerType; private Date timeCreated = new Date( ); private File picture; @Id
kjoundi@yahoo.com

IGA 2009/2010

Page 2

EJB3
@GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } }

IGA 2009/2010

public void setId(Long id) {

this.id = id;

@Enumerated(EnumType.STRING) public CustomerType getCustomerType() { return customerType; }

public void setCustomerType(CustomerType customerType) { this.customerType = customerType; } public String getFirstName() { return firstName; } }

public void setFirstName(String firstName) { public String getLastName() {

this.firstName = firstName; } }

return lastName;

public void setLastName(String lastName) { @Lob @Basic(fetch=FetchType.LAZY) public File getPicture() { return picture; }

this.lastName = lastName;

public void setPicture(File picture) {

this.picture = picture;

@Temporal(javax.persistence.TemporalType.TIME) public Date getTimeCreated() { return timeCreated; }

public void setTimeCreated(Date timeCreated) { this.timeCreated = timeCreated; } }

package com.domain6; public enum CustomerType { UNREGISTERED, REGISTERED, BIG_SPENDAH }

kjoundi@yahoo.com

Page 3

EJB3

IGA 2009/2010

The @javax.persistence.Enumerated annotation is used here to tell the persistence provider that we want to store it as a string in the database. A java.util.Date can be stored in different ways in the database, so here we specify that we want the database to store it as a time SQL type, using the @javax.persistence.Temporal annotation . By marking the Customer's picture property as an @Lob , the persistence provider will see that picture is a serializable Java object and will map it to an SQL Blob type in the database. Step2 : Add ManageCustomer1 Stateless session Bean class to persist and find Customer Entity Bean package com.domain6; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class ManageCustomer1Bean implements ManageCustomer1Remote { @PersistenceContext(unitName="EJBCHAP6PU") EntityManager manager; public void create(Object object) { public Customer1 find( Long pk){ }} manager.persist(object); }

return manager.find(Customer1.class, pk) ;

package com.domain6; import javax.ejb.Remote; @Remote public interface ManageCustomer1Remote { public void create(java.lang.Object object);

kjoundi@yahoo.com

Page 4

EJB3
public com.domain6.Customer1 find(java.lang.Long pk); } Step 3:Add a Main class (Main1.java ) to your application client module. public class Main1 { @EJB private static ManageCustomer1Remote manageCustomer1Bean; public static void main(String[] args) { Customer1 cust = new Customer1(); cust.setFirstName("Assad"); cust.setLastName("Dracula"); cust.setCustomerType(CustomerType.REGISTERED); //

IGA 2009/2010

File image1 = new File("C:/UMLProject/EJBCHAP6/EJBCHAP6-appclient/src/java/images/Dell_Badge.bmp"); cust.setPicture(image1); cust.setTimeCreated(new Date()); // persisting Cusomer Object (with a Blob Object attribute) manageCustomer1Bean.create(cust) ; File x= manageCustomer1Bean.find(new Long(1)).getPicture() ; // store is a directory File store = new File("C:/UMLProject/EJBCHAP6/EJBCHAP6-appclient/src/java/store"); store.mkdir(); try { copier(x, new File(store, "copieimage.bmp"));
kjoundi@yahoo.com Page 5

EJB3
} catch (IOException ex) {

IGA 2009/2010

Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } public static void copier(File ficLu, File ficEcrit) throws IOException{ FileInputStream read = new FileInputStream(ficLu); int TMAX = 5000; byte[] tabLu = new byte[TMAX]; int nbLu ; try { FileOutputStream write = new FileOutputStream(ficEcrit); try { while((nbLu = read.read(tabLu)) > 0){ write.write(tabLu,0,nbLu); write.flush(); } } finally { write.close(); } } finally { read.close(); } }

Step 3 : Run your Application Part 2:


kjoundi@yahoo.com Page 6

EJB3

IGA 2009/2010

This part shows you an example of using @javax.persistence.IdClass to map a primary key class to the database. Step 1: Add /Examine Customer2 Entity class and CustomerPK class package com.domain6; import com.domain6.Customer2; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.Table; @Entity @Table(name="Customer2") @IdClass(CustomerPK.class) public class Customer2 implements Serializable { private Long id; private String firstName; private String lastName; private long ssn; @Id public Long getId() { return id; } } }

public void setId(Long id) { public String getFirstName() {

this.id = id;

return firstName;

kjoundi@yahoo.com

Page 7

EJB3
public void setFirstName(String firstName) { @Id public String getLastName() { return lastName; }

IGA 2009/2010
this.firstName = firstName; }

public void setLastName(String lastName) { @Id public long getSsn() { return ssn; }

this.lastName = lastName;

public void setSsn(long ssn) { }

this.ssn = ssn;

package com.domain6; import java.io.Serializable; public class CustomerPK implements Serializable{ private long ssn; private String lastName ; public String getLastName() { return lastName; } }

public void setLastName(String lastName) { public long getSsn() { return ssn; }

this.lastName = lastName;

public void setSsn(long ssn) { public CustomerPK() { }

this.ssn = ssn;

public CustomerPK(String lastName, long ssn) { this.lastName = lastName; this.ssn = ssn; } public boolean equals(Object obj)
kjoundi@yahoo.com Page 8

EJB3
{ if (obj == this) return true; if (!(obj instanceof CustomerPK)) return false; CustomerPK pk = (CustomerPK)obj; if (!lastName.equals(pk.lastName)) return false; if (ssn != pk.ssn) return false; return true; } public int hashCode( ) { } return lastName.hashCode( ) + (int)ssn; }

IGA 2009/2010

Step2: Add ManageCustomer2 Stateless session Bean class to persist and find Customer Entity Bean

package com.domain6; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class ManageCustomer2Bean implements ManageCustomer2Remote{ @PersistenceContext (unitName="EJBCHAP6PU") EntityManager manager; public void create(Customer2 cust){ manager.persist(cust); return }

public Customer2 find (CustomerPK pk){ manager.find(Customer2.class,pk); } }


kjoundi@yahoo.com

Page 9

EJB3

IGA 2009/2010

@Remote public interface ManageCustomer2Remote { public void create(com.domain6.Customer2 cust); public com.domain6.Customer2 find(com.domain6.CustomerPK pk); } Step 3 : Add a Main class (Main2.java ) to your application client module.

package ejbchap6; import com.domain6.Customer2; import com.domain6.CustomerPK; import com.domain6.ManageCustomer2Remote; import javax.ejb.EJB; public class Main2 { @EJB private static ManageCustomer2Remote manager; public static void main(String args[]){ Customer2 cust = new Customer2(); cust.setFirstName("Bill"); cust.setLastName("Burke"); cust.setSsn(999); manager.create(cust); Customer2 cust2; cust2 = manager.find(new CustomerPK("Burke", 999));
kjoundi@yahoo.com Page 10

EJB3
System.out.println(cust2.getFirstName()); System.out.println(cust2.getLastName()); System.out.println(cust2.getSsn()); } } Part 3:

IGA 2009/2010

This part 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. Step 1: Add / Examine Customer3 Entity class and Customer3PK class

package com.domain6; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class Customer3PK implements Serializable { private String lastName; private long ssn; public Customer3PK() { }

public Customer3PK(String lastName, long ssn) { this.lastName = lastName; this.ssn = ssn; } @Column(name="CUSTOMER_LAST_NAME") public String getLastName() { return lastName; public void setLastName(String lastName) { @Column(name="CUSTOMER_SSN") public long getSsn() { return ssn; } public void setSsn(long ssn) { this.ssn = ssn; }

} }

this.lastName = lastName;

public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Customer3PK)) return false; Customer3PK pk = (Customer3PK)obj; if (!lastName.equals(pk.lastName)) return false;
kjoundi@yahoo.com Page 11

EJB3
if (ssn != pk.ssn) return false; return true; } public int hashCode() } { return lastName.hashCode() + (int)ssn;

IGA 2009/2010

package com.domain6; import java.io.Serializable; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Transient; @Entity public class Customer3 implements Serializable { private Long id; private String firstName; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; private Customer3PK 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 Customer3PK getPk() { return pk; } public void setPk(Customer3PK pk) { public Long getId() { return id; } } this.pk = pk; }

public void setId(Long id) { @Transient public String getLastName(){


kjoundi@yahoo.com

this.id = id;

return pk.getLastName(); }
Page 12

EJB3
@Transient public long getSsn(){ }

IGA 2009/2010
}

return pk.getSsn();

Step2: Add ManageCustomer3 Stateless session Bean class to persist and find Customer3 Entity Bean Step 3 : Add a Main class (Main3.java ) to your application client module. Step 4 : Run your application

Part 4: This part demonstrates how you can use the


@javax.persistence.SecondaryTable and @SecondaryTables

annotation to map

one entity class to multiple tables. Step 1: Add / Examine Customer4 Entity class and Customer3PK class

package com.domain6; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.Table; @Entity @Table(name="CUSTOMER4_TABLE") @SecondaryTable(name="AdressTable",pkJoinColumns={ @PrimaryKeyJoinColumn(name="ADDRESS_ID",referencedColumnName="id") }) public class Customer4 implements Serializable { private long id; private String firstName; private String lastName;
kjoundi@yahoo.com Page 13

EJB3
private String street; private String city; private String state; @Column(name="CITY",table="AdressTable") public String getCity() { return city; } public void setCity(String city) { this.city = city; }

IGA 2009/2010

public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Column(name="STATE",table="AdressTable") public String getState() { return state; } public void setState(String state) { this.state = state; @Column(name="STREET",table="AdressTable") public String getStreet() { return street; } public void setStreet(String street) { } Step2: Add ManageCustomer4 Stateless session Bean class to persist and find Customer4 Entity Bean Step 3 : Add a Main class (Main4.java) to your application client module. Step 4: Run your application }

this.street = street; }

For more than one secondary table: For example, let's say that you want to embed credit card properties, but this information was also stored in another table. In that instance, you would use the @SecondaryTables annotation:
kjoundi@yahoo.com Page 14

EJB3
Example to complete:

IGA 2009/2010

@Entity @Table(name="CUSTOMER_TABLE") @SecondaryTables({ @SecondaryTable(name="ADDRESS_TABLE", pkJoinColumns={@PrimaryKeyJoinColumn (name="ADDRESS_ID")}), @SecondaryTable(name="CREDIT_CARD_TABLE", pkJoinColumns={@PrimaryKeyJoinColumn (name="CC_ID")}) }) public class Customer

Part 5: This part demonstrates how you can use the @javax.persistence.Embedded annotation to map a persistent property that is a nonentity class. Step 1: Add / Examine Customer5 Entity class and Address5Embeddable class. package com.domain6; import java.io.Serializable; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.GenerationType; @Entity public class Customer5 implements Serializable{ private long id; private String firstName; private String lastName;

kjoundi@yahoo.com

Page 15

EJB3
private Address5Embeddable address; @Embedded @AttributeOverrides({ @AttributeOverride(name="street", column=@Column(name="STREETCOLUMN")),

IGA 2009/2010

@AttributeOverride(name="city", column=@Column(name="CITYCOLUMN")), @AttributeOverride(name="state", column=@Column(name="STATECOLUMN")) }) public Address5Embeddable getAddress() { return address; } }

public void setAddress(Address5Embeddable address) { this.address = address; public String getFirstName() { return firstName; } }

public void setFirstName(String firstName) { @Id

this.firstName = firstName;

@GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } } }

public void setId(long id) { public String getLastName() {

this.id = id;

return lastName;

public void setLastName(String lastName) { }}

this.lastName = lastName;

package com.domain6; import java.io.Serializable; import javax.persistence.Column;


kjoundi@yahoo.com Page 16

EJB3
import javax.persistence.Embeddable; @Embeddable public class Address5Embeddable implements Serializable{ private String street; private String city; private String state; @Column(name="CITY") public String getCity() { return city; } }

IGA 2009/2010

public void setCity(String city) { @Column(name="STATE") public String getState() {

this.city = city;

return state;

} }

public void setState(String state) { @Column(name="STREET") public String getStreet() {

this.state = state;

return street;

} }

public void setStreet(String street) { }

this.street = street;

Step2: Add ManageCustomer5 Stateless session Bean class to persist and find Customer5 Entity Bean Step 3 : Add a Main class (Main5.java) to your application client module. Step 4: Run your application

The End(yotba3)
kjoundi@yahoo.com Page 17

Вам также может понравиться