June 1, 2011

EJB3 Entity Beans - Hello World Example

0) Download the Oracle Database 10g Express Edition and setup according to instructions on this link

1) Create a new Java Project named JPAdemo, in Eclipse. Click Finish.

Add the Oracle JDBC driver jar(ojdbc14.jar) to the build path of the project. This jar file is present at the following path of the Oracle installation - %ORACLE_HOME%\app\oracle\product\10.2.0\server\jdbc\lib

Also, add all the jars files present in the JBoss-4.2.2GA application server at the following paths:
- %JBOSS_HOME%\lib
- %JBOSS_HOME%\server\default\lib

2) Create a new class, Message.java in the src folder of the project. This class is the Entity Bean or the persistent class / entity according to the Java Persistence API (JPA) terminology.
The annotations in this class are equivalent to the configurations in the hibernate mapping files of the Hibernate persistence framework.


package info.icontraining.entity;


import javax.persistence.*;


@Entity
@Table(name="MESSAGES_TABLE_JPA")
public class Message {


    @Id
    @GeneratedValue
    @Column(name="MESSAGE_ID")
    private Long id;

    @Column(name="MESSAGE_TEXT")
    private String text;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="NEXT_MESSAGE_ID")
    private Message nextMessage;

    private Message() { }

    public Message(String text) {
        this.text = text;
    }


    public Long getId() {
        return id;
    }


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


    public String getText() {
        return text;
    }


    public void setText(String text) {
        this.text = text;
    }


    public Message getNextMessage() {
        return nextMessage;
    }


    public void setNextMessage(Message nextMessage) {
        this.nextMessage = nextMessage;
    }
}


3) Create another class - Client.java - within the src folder. This class contains code to persist entities (or persistent objects) to the database table and retrieve data into persistent objects from the database table.


package info.icontraining.client;


import java.util.List;
import info.icontraining.entity.*;


import javax.persistence.*;


public class Client {


    public static void main(String[] args) {

        EntityManagerFactory emf = 
               Persistence.createEntityManagerFactory("JPAdemo");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        Message msg = new Message("Hello World");
        em.persist(msg);

        tx.commit();
        em.close();

        EntityManager newEm = emf.createEntityManager();
        EntityTransaction newTx = newEm.getTransaction();

        newTx.begin();

        List msgs = newEm.createQuery
           ("select m from Message m order by m.text asc").getResultList();

        System.out.println(msgs.size() + " messages found.");

        for(Object m: msgs) {
            Message loadedMsg = (Message)m;
            System.out.println(loadedMsg.getText());
        }

        newTx.commit();
        newEm.close();

        emf.close();
    }
}


4) Add the following XML configuration file, named persistence.xml within the src\META-INF folder


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="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 http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
   <persistence-unit name="JPAdemo">
      <properties>
        <property name="hibernate.archive.autodetection" value="class,hbm" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="true" />
        <property name="hibernate.connection.driver_class" 
                          value="oracle.jdbc.OracleDriver" />
        <property name="hibernate.connection.url" 
                          value="jdbc:oracle:thin:@localhost:1521:xe" />
        <property name="hibernate.connection.username" value="xxxxx" />
        <property name="hibernate.connection.password" value="xxxxx" />
        <property name="hibernate.dialect" 
                          value="org.hibernate.dialect.Oracle9Dialect" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.generate_statistics" value="true" />
        <property name="cache.provider_class" 
                          value="org.hibernate.cache.NoCacheProvider" />
      </properties>
   </persistence-unit>
</persistence>


5) Run the Client.java class as a standalone Java program to test the Entity Bean

No comments:

Post a Comment