Thursday, May 5, 2016

JAVA Entity Class Creation Technique For Simple Key and Composite Key Tables

This is quite advanced topic.  But this is the blog for making advanced topic into a simple topic !!! 



My Environment is as follows:

1. EJB 3.0 containing stateless remote session bean.

2. Data Source.

3. Entity Class for table in Oracle RDBMS.

4. JBOSS 6 Application Server

5. A console based application to test the bean.

Entity class is a persistent object or POJO which  represents the data-stores record of a table. It is good to be a serializable.

You can simply say that an Entity class contains a single data record of a table in a RDBMS Or data storing (persistence) class in JAVA programming language. 

Please don't be confused of term POJO (Plain Old Java Object). POJO means that a class never be subclass or implements any class methods. It has just class-level variables and corresponding getter setter methods. For example:

// A Sample POJO Class
public class ClassA
{
         private String name;
         private String address;

         public ClassA()
        {
                    //Code
         }

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

         public String getName()
        {
                   return name;
         }

         public setAddress(String address)
        {
                    this.address = address;
         }

         public String getAddress()
        {
                    return address;
         }
}

To create Entity Class we'll use this type of class. Just adding few @annotaions.

And 1 more thing, to use Entity Class (for DML opeartions), you have to  EntityManager persistent interface to add/delete/update/find. But this is not our topic.

Now we'll create Entity class for simple key table that means only 1 column is primary key.


CREATE TABLE   books (   id     integer PRIMARY KEY,   name   varchar(50));


Now, i'll create an entity class for books. I'll use following annotations.

@Entity: defines this POJO class is an entity.

@Table (name="books"): specify the table name.

@Column (name="name"): specify the column name.

@Id: defines the primary key property of a table.

@Basic(optional=false): if is followed by @Id. It tells that no sequence generated for primary key that means the value of primary key filed will be set manually.

Using the above r annotations, i'll create an entity class of the table: books.



           import java.io.Serializable;
           import java.math.BigDecimal;
           import javax.persistence.*;
@Entity                                           // defines this is an entity class
@Table(name="books")                 // defines the table name  
public class Book implements Serializable {  
    
    @Id                                             // defines this is a primary key field
    @Basic(optional = false)            // defines the value not auto generated
    @Column(name="id")                // defines the column name
    private BigDecimal id;
    
    @Column(name="name")          // defines the column name

    private String name;

    public Book() {
    }

    
    public BigDecimal getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

Now i'll create a composite primary key table.


create table MyPersistentTable
          (
   id integer,
   trn_ref_no varchar2(50),
   amount number,
   primary key(id, trn_ref_no)
);
The above table has composite primary key of two columns.There is 2 techniques to create entity class for above table.

1st Technique

Just create an entity class of MyPersistentTable table just  like before example.


@Entity
@Table(name="MyPersistentTable")
public class MyTable1 implements Serializable {
    
    @Id
    @Basic(optional=false)
    @Column(name="id")
    private int id;
    
    @Id
    @Basic(optional=false)
    @Column(name="trn_ref_no")
    private String refNo;
    
    @Column(name="amount")
    private BigDecimal price;

    public MyTable1() {
    }

    public int getId() {
        return id;
    }

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

    public String getRefNo() {
        return refNo;
    }

    public void setRefNo(String refNo) {
        this.refNo = refNo;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }
}


2nd Technique

In this approach i'll create another class for 2 field primary keys (id + trn_ref_no) in MyPersistentTable table. And i tell the entity class that the new class is id class.

The fields inside the new class will be used as id/keys.

I use the annotation @Embeddable for the new class

@Embeddable annotation specifies that the class will be id class.

And i tell the entity class using annotation @EmbeddedId about the id class.

@EmbeddedId annotation used to define id class in entity class.

In our case, id class is following:


@Embeddable
public class MyTable2PK implements Serializable{
    
    
    @Basic(optional=false)
    @Column(name="id")
    private int id;
    
    
    @Basic(optional=false)
    @Column(name="trn_ref_no")
    private String refNo;

    public MyTable2PK() {
    }

    public int getId() {
        return id;
    }

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

    public String getRefNo() {
        return refNo;
    }

    public void setRefNo(String refNo) {
        this.refNo = refNo;
    }    
}


And Entity class is as follows:



@Entity
@Table(name="MyPersistentTable")
public class MyTable2 implements Serializable {
    
    @EmbeddedId
    protected MyTable2PK pk;
    
    
    @Column(name="amount")
    private BigDecimal price;

    public MyTable2() {
    }

    public MyTable2PK getPk() {
        return pk;
    }

    public void setPk(MyTable2PK pk) {
        this.pk = pk;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }
}




My bean class is so simple to add/select data from table using above entity class.

@Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {

    public LibraryPersistentBean() {
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    @PersistenceContext(unitName="EjbComponentPU")
    private EntityManager manager;
    
    @PersistenceContext(unitName="EjbComponentPU")
    private EntityManager mgr1;
    
    @Override
    public List getBooks() {
        return manager.createQuery("Select b From Book b").getResultList();
    }

    @Override
    public void addBook(Book book) {
        
        manager.persist(book);
    }

    @Override
    public void addMyTable1(MyTable1 myTable) {
        mgr1.persist(myTable);
    }

    @Override
    public List getMyTables1() {
        return mgr1.createQuery("select t from MyTable1 t").getResultList();
    }

    @Override
    public void addMyTable2(MyTable2 MyTable) {
        manager.persist(MyTable);
    }

    @Override
    public List getMyTables2() {
        return manager.createQuery("select t from MyTable2 t").getResultList();
    }  
}


And that is all about entity class.

2 comments: