Thursday, January 31, 2008

EJB3 + JPA on OC4J with Client

Thursday, January 31, 2008 Posted by Andre Broers , 26 comments
Let's use the previous JPA sample in an EJB. We start creating a datasource on the OC4J container. Then we create the entities again. After this we use the entities in a Stateless EJB which we will deploy to OC4J 11g. Finally we create a stand-alone client which calls the EJB.

We start with the creation of the datasource. We need a ConnectionPool.

java -jar $OC4J_ADMIN/j2ee/home/admin_client.jar deployer:oc4j:localhost oc4jadmin welcome -CreateJDBCConnectionPool -applicationName default -name HrConnectionPool -factoryClass oracle.jdbc.pool.OracleDataSource -user hr -password hr -url jdbc:oracle:thin:@localhost:1521:orcl

Test the connectionpool:

java -jar $OC4J_ADMIN/j2ee/home/admin_client.jar deployer:oc4j:localhost oc4jadmin welcome
-testConnectionPool -connectionPoolName HrConnectionPool -sqlStatement "select
* from dual" And the datasource:

java -jar $OC4J_ADMIN/j2ee/home/admin_client.jar deployer:oc4j:localhost oc4jadmin welcome -createManagedDataSource -applicationName default -dataSourceName HrDataSource -jndiLocation jdbc/HrDataSource -connectionPoolName HrConnectionPool

After this we create the entities:

/home/broersa/work/CountryApp/CountryJPAEJB/src/com/bekijkhet/entity/Country.java:

[sourcecode language="java"]

package com.bekijkhet.entity;

import java.io.Serializable;
import javax.persistence.*;

@Entity
@Table(name="COUNTRIES")
public class Country implements Serializable {
private String id;
private String name;
private Region region;

@Id
@Column(name="COUNTRY_ID")
public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

@Column(name="COUNTRY_NAME")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="REGION_ID",nullable=false)
public Region getRegion() {
return region;
}

public void setRegion(Region region) {
this.region = region;
}
}

[/sourcecode]
/home/broersa/work/CountryApp/CountryJPAEJB/src/com/bekijkhet/entity/Region.java
[sourcecode language="java"]

package com.bekijkhet.entity;

import java.io.Serializable;
import javax.persistence.*;
import static javax.persistence.CascadeType.*;
import static javax.persistence.FetchType.*;

import java.util.List;
import java.util.ArrayList;

@Entity
@Table(name="REGIONS")
public class Region implements Serializable {
private int id;
private String name;
private List countries = new ArrayList();;

@Id
@Column(name="REGION_ID")
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Column(name="REGION_NAME")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@OneToMany(fetch=FetchType.EAGER, cascade={CascadeType.ALL}, mappedBy="region")
public List getCountries() {
return countries;
}

public void setCountries(List newValue) {
this.countries = newValue;
}
}[/sourcecode]
The EJB:/home/broersa/work/CountryApp/CountryJPAEJB/src/com/bekijkhet/country/CountryEJBLocal.java:
[sourcecode language="java"]

package com.bekijkhet.country;

import com.bekijkhet.entity.*;
import java.util.List;

public interface CountryEJBLocal {
public List getCountriesByRegion(String region);
public Region getRegionByCountry(String country);
}[/sourcecode]
/home/broersa/work/CountryApp/CountryJPAEJB/src/com/bekijkhet/country/CountryEJB.java:
[sourcecode language="java"]

package com.bekijkhet.country;
import java.util.List;
import com.bekijkhet.entity.*;
public interface CountryEJB {
public List getCountriesByRegion(String region);
public Region getRegionByCountry(String country);
public void addorchangeCountry(Country country) ;
public void addorchangeRegion(Region region) ;
public void removeCountry(Country country) ;
public void removeRegion(Region region) ;
public List getAllRegions() ;
public List getAllCountries();
}[/sourcecode]
/home/broersa/work/CountryApp/CountryJPAEJB/src/com/bekijkhet/country/CountryEJBBean.java
[sourcecode language="java"]

package com.bekijkhet.country;
import javax.ejb.Stateless;
import javax.ejb.Remote;
import javax.ejb.Local;

import java.util.List;
import com.bekijkhet.entity.*;
import javax.persistence.*;

@Stateless
@Remote(CountryEJB.class)
@Local(CountryEJBLocal.class)
public class CountryEJBBean implements CountryEJB,CountryEJBLocal {
@PersistenceContext
EntityManager em;

public List getCountriesByRegion(String region) {
Query q = em.createQuery("select r from Region r where r.name = :name");
q.setParameter("name",region);
Region r = (Region) q.getSingleResult();
// r.getCountries().size(); // get the LAZY relation
return r.getCountries();
}

public Region getRegionByCountry(String country) {
Query q = em.createQuery("select c from Country c where c.name = :name");
q.setParameter("name",country);
Country c = (Country) q.getSingleResult();
return c.getRegion();
}

public void addorchangeCountry(Country country) {
em.persist(country);
}

public void addorchangeRegion(Region region) {
em.persist(region);
}

public void removeCountry(Country country) {
Country c = em.merge(country);
em.remove(c);
}

public void removeRegion(Region region) {
Region r = em.merge(region);
em.remove(r);
}

public List getAllRegions() {
Query q = em.createQuery("select r from Region r");
List l = q.getResultList();
return l;
}

public List getAllCountries() {
Query q = em.createQuery("select c from Country c");
List l = q.getResultList();
return l;
}
}

[/sourcecode]
We need a persistence descriptor : /home/broersa/work/CountryApp/CountryJPAEJB/src/META-INF/persistence.xml:
[sourcecode language="XML"]


jdbc/HrDataSource

[/sourcecode]
We need the build file:/home/broersa/work/CountryApp/CountryJPAEJB/build.xml:
[sourcecode language="XML"]



simple example build file



















description="compile the source " >






description="generate the distribution" >












description="clean up" >






[/sourcecode]
We can build and deploy the EJB:type "ant" to build the EJB.use the next command to deploy the ejb:

java -jar $OC4J_ADMIN/j2ee/home/admin_client.jar deployer:oc4j:localhost oc4jadmin welcome -deploy -file $HOME/work/CountryApp/CountryJPAEJB/dist/CountryBean.jar -deploymentName CountryBean

Now this is done we can create the client:

/home/broersa/work/CountryApp/CountryClient/com/bekijkhet/CountryClient.java:

[sourcecode language="java"]

package com.bekijkhet;
import javax.naming.*;
import com.bekijkhet.country.CountryEJB;
import com.bekijkhet.entity.*;
import java.util.Properties;
import java.util.List;

public class CountryClient {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.put("java.naming.factory.initial","com.evermind.server.ApplicationClientInitialContextFactory");
props.put("java.naming.provider.url","ormi://localhost/CountryBean");
props.put("java.naming.security.principal","oc4jadmin");
props.put("java.naming.security.credentials","welcome");
InitialContext ctx = new InitialContext(props);
CountryEJB h = (CountryEJB)ctx.lookup("CountryEJBBean");

System.out.println("The Netherlands has region: " + h.getRegionByCountry("Netherlands").getName());
List l1 = h.getCountriesByRegion("Europe");
System.out.println("Europe has the following countries:");
for (Country c : l1) {
System.out.println(" " + c.getName());
}
System.out.println("All regions:");
List l2 = h.getAllRegions();
for (Region r : l2) {
System.out.println(" " + r.getName());
}
System.out.println("All countries:");
List l3 = h.getAllCountries();
for (Country c2 : l3) {
System.out.println(" " + c2.getName() + " - " + c2.getRegion().getName());
}

Region r3 = new Region();
r3.setName("MyRegion1");
r3.setId(1001);
Country c3 = new Country();
c3.setName("MyCountry1");
c3.setId("31");
c3.setRegion(r3);
r3.getCountries().add(c3);
h.addorchangeCountry(c3);

Region r4 = new Region();
r4.setName("MyRegion2");
r4.setId(1002);
Country c4 = new Country();
c4.setName("MyCountry2");
c4.setId("32");
c4.setRegion(r4);
r4.getCountries().add(c4);
h.addorchangeRegion(r4);

System.out.println("All regions:");
List l5 = h.getAllRegions();
for (Region r5 : l5) {
System.out.println(" " + r5.getName());
}
System.out.println("All countries:");
List l6 = h.getAllCountries();
for (Country c6 : l6) {
System.out.println(" " + c6.getName() + " - " + c6.getRegion().getName());
}
}
catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
}

[/sourcecode]
/home/broersa/work/CountryApp/CountryClient/com/bekijkhet/META-INF/application-client.xml:
[sourcecode language="XML"]

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/application-client_1_4.xsd">
CountryClient
test
[/sourcecode]
Compile the client:javac -cp $OC4J_HOME/j2ee/home/oc4jclient.jar:/home/broersa/work/CountryApp/CountryJPAEJB/dist/CountryBean.jar:. -d . CountryClient.javaAnd test the client:java -cp $OC4J_HOME/j2ee/home/oc4jclient.jar:/home/broersa/work/CountryApp/CountryJPAEJB/dist/CountryBean.jar:. com.bekijkhet.CountryClient

The Netherlands has region: Europe
Europe has the following countries:
Belgium
Switzerland
Germany
Denmark
France
Italy
Netherlands
United Kingdom
All regions:
Europe
Americas
Asia
Middle East and Africa
All countries:
Argentina - Americas
Australia - Asia
Belgium - Europe
Brazil - Americas
Canada - Americas
Switzerland - Europe
China - Asia
Germany - Europe
Denmark - Europe
Egypt - Middle East and Africa
France - Europe
HongKong - Asia
Israel - Middle East and Africa
India - Asia
Italy - Europe
Japan - Asia
Kuwait - Middle East and Africa
Mexico - Americas
Nigeria - Middle East and Africa
Netherlands - Europe
Singapore - Asia
United Kingdom - Europe
United States of America - Americas
Zambia - Middle East and Africa
Zimbabwe - Middle East and Africa
All regions:
Europe
Americas
Asia
Middle East and Africa
MyRegion1
MyRegion2
All countries:
MyCountry1 - MyRegion1
MyCountry2 - MyRegion2
Argentina - Americas
Australia - Asia
Belgium - Europe
Brazil - Americas
Canada - Americas
Switzerland - Europe
China - Asia
Germany - Europe
Denmark - Europe
Egypt - Middle East and Africa
France - Europe
HongKong - Asia
Israel - Middle East and Africa
India - Asia
Italy - Europe
Japan - Asia
Kuwait - Middle East and Africa
Mexico - Americas
Nigeria - Middle East and Africa
Netherlands - Europe
Singapore - Asia
United Kingdom - Europe
United States of America - Americas
Zambia - Middle East and Africa
Zimbabwe - Middle East and Africa

26 comments:

  1. Hi,thanks for all your samples, it's very usefull !

    However, I have a problem with these examples : I package them in a .WAR archive (I even tried on a .EAR), when I deploy them on OC4J, everything work fine. If I redeploy a second tim, I have an exception from TopLink saying that it cannot find my entity beans ... Am I missing something ?

    ReplyDelete
  2. I don't have a clue. Maybe someone else who reads this blog?

    ReplyDelete
  3. Container setup for 10g (may be usefull):

    set ADM=%ORACLE_HOME%/j2ee/home/admin_client.jar
    set DEPLOYER_URI=deployer:oc4j:localhost oc4jadmin admin
    set URL=jdbc:oracle:thin:@localhost:1521:na7
    set CONN_POOL=na7ConnectionPool

    :We start with the creation of the datasource. We need a ConnectionPool.

    java -jar %ADM% %DEPLOYER_URI% -addDataSourceConnectionPool^
    -applicationName default -name %CONN_POOL% -factoryClass^
    oracle.jdbc.pool.OracleDataSource -dbUser od -dbPassword od -url %URL%


    :::: Test the connectionpool:

    java -jar %ADM% %DEPLOYER_URI% -testDataSourceConnectionPool -name %CONN_POOL% -sqlStatement "select * from dual"

    :::: And the datasource:

    java -jar %ADM% %DEPLOYER_URI% -addManagedDataSource -name na7DataSource -jndiLocation^
    jdbc/na7DataSource -connectionPoolName %CONN_POOL%

    ReplyDelete
  4. P.S. I try replace it by
    props.put(”java.naming.security.principal”,”oc4jadmin”);
    props.put(”java.naming.security.credentials”,”welcome”);

    nothing changed...

    ReplyDelete
  5. I changed the password, and removed your quote with the password in it. You are right. The last password must be welcome. I forgot to change it before posting ;-)

    ReplyDelete
  6. Excellent post!!! Java is most popular and efficient programming language available in the market today. It helps developers to create stunning desktop/web applications loaded with stunning functionalities. Best JAVA Training in Chennai | JAVA Course in Chennai

    ReplyDelete
  7. Upgrading ourselves to the upcoming technology is the best way to survive in this modern and fast paced technology world. Reading contents like this will create a positive impact within me. Thanks for writing such a valuable content. Keep up this work.

    JAVA Training in Chennai | | JAVA Course in Chennai | JAVA Training Institutes in Chennai | Best JAVA Training institute in Chennai

    ReplyDelete
  8. Great post on Java and the code which have written is asewsome. IICT chromepet is the No.1 Java Training Institute in Chennai. I read the complete blog it was really great and awesome. Thanks a lot. Mr.Senthil and Mani are the jav experts who work for TCS in java technology for more than 10+ years.

    Regards,
    iOS Training in Chennai | Multimedia Training in Chennai | | Informatica Training in Chennai | CCNA Training in Chennai | Java Training in Chennai | Oracle Training in Chennai | Android Training in Chennai

    ReplyDelete
  9. I am following your blog from the beginning, it was so distinct & I had a chance to collect conglomeration of information that helps me a lot to improvise myself.
    Regards,
    CCNA Training in Chennai | CCNA Training Institute in Chennai | Best CCNA Training in Chennai

    ReplyDelete
  10. Excellent article.It has a lot of important information with creative concept.I will read this information and is good using the concept.
    Regards,
    QTP Training in Chennai | Informatica Training in Chennai | Android Training in Chennai

    ReplyDelete
  11. iFlyChat is an ongoing talk module most appropriate for group and long range informal communication sites. It helps in expanding client engagement of your WordPress site by empowering clients to visit with each other secretly (balanced private discussion), bunch talk or in talk rooms
    Wp Chat

    ReplyDelete
  12. Excellent write-up as well as excellent site,affordable seo packages I enjoy these types of demanding content hold this unique somebody.

    ReplyDelete
  13. I gone through your blog it is really superb. I am so happy to read your blog.. I am planning to do R-Programming Training in Chennai please help me out with course content. I heard IICT is the best R-Programming Training Institute in Chennai. I heard IICT is the leading Data Analytics training institute in chennai.

    ReplyDelete
  14. nice article about apj.
    Best SEO training in hyderabad all modules are clearly solved and practice with guide.seo training in hyderabadAnd clearly getting knowledge of seo.

    ReplyDelete
  15. Everyone loves it when individuals come together and share thoughts. Great blog, continue the good work!
    salesforce training in hyderabad

    ReplyDelete
  16. Useful Information
    one and only affiliate agency in south INDIA, earn money online from affiliate network in india

    ReplyDelete
  17. Freshers jobs way provide freshers jobs ,walkins,direct recruitment,openings for freshers and experienced and recruiting experienced and freshers Walkins

    ReplyDelete
  18. useful information

    Online recruitment for bank jobs and government jobs and you can get Notification and application to apply online for bank jobs and govt jobs

    ReplyDelete
  19. Useful information:
    General Awareness and Current Affairs with Latest Current Affairs Quiz, GK Updates, General Knowledge Last 6 Months Current Affairs, Placement Papers, Model Papers, Interview Questions @ examvalue.com

    ReplyDelete
  20. Java Training Institutes Java Training Institutes Java EE Training in Chennai Java EE Training in Chennai Java Spring Hibernate Training Institutes in Chennai J2EE Training Institutes in Chennai J2EE Training Institutes in Chennai Core Java Training Institutes in Chennai Core Java Training Institutes in Chennai

    ReplyDelete
  21. Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training

    Hibernate Online Training Hibernate Online Training Spring Online Training Spring Online Training Spring Batch Training Online Spring Batch Training Online

    ReplyDelete