1 Temmuz 2014 Salı

OpenJPA

The tutorial from which I learnt openJPA was mentioning about Apache Derby. I have written a small intro about Apache Derby in the following link ;)

Data is the most important part of all programs. We have been using databases and SQL statements for years. However, better approaches exists! Especially object-oriented approaches for data persistence is very useful.

Some examples: EJB, JDO, Hibernate, Toplink... (The last 2 are object-relational mapping tool)

Java persistence API = JPA (standard)
first introduced as a part of EJB 3.0.

openJPA is another solution for data persistency. There are 3 artifacts:
  1. entity class
  2. persistence.xml (in src/META-INF)
  3. A class through which you will insert, update or find an entity.

  • Firstly, we should download openJPA from the following link:
http://openjpa.apache.org/downloads.html

  • Then add the jars to the project's build-path.

Let's say we have a DB table CUSTOMER:

NAMEPK?TYPENULL?
CUST_IDYINTEGERNOT NULL
FIRST_NAMEVARCHAR(50)NOT NULL
LAST_NAMEVARCHAR(50)
STREETVARCHAR(50)
APPTVARCHAR(20)NOT NULL
CITYVARCHAR(25)
ZIP_CODEVARCHAR(10)NOT NULL
CUST_TYPEVARCHAR(10)NOT NULL
LAST_UPDATED_TIMETIMESTAMPNOT NULL

Now we should have an entity class like this:

package entity;
import javax.persistence.*;

import java.io.Serializable;
import java.util.Date;
/*
 * CUSTOMER ENTITY CLASS
 */
@EntityListeners({CustListner.class})
@Entity(name = "CUSTOMER") //Name of the entity
public class Customer implements Serializable{
@Id //signifies the primary key
@Column(name = "CUST_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long custId;
@Column(name = "FIRST_NAME", nullable = false,length = 50)
private String firstName;
@Column(name = "LAST_NAME", length = 50)
private String lastName;
@Embedded
private Address address = new Address();
@Column(name = "CUST_TYPE", length = 10)
private String custType;
@Version
@Column(name = "LAST_UPDATED_TIME")
private Date updatedTime;

//Getters and setters
public long getCustId() {
return custId;
}

public void setCustId(long custId) {
this.custId = custId;
}

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 Date getUpdatedTime() {
return updatedTime;
}

public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public String getCustType() {
return custType;
}

public void setCustType(String custType) {
this.custType = custType;
}
// ToString()
public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append("custId : " + custId);
      sb.append("   First Name : " + firstName);
      sb.append("   Last Name : " + lastName);
      sb.append("   customer type : " + custType);

      return sb.toString();
   }
}

And here is the sample persistence.xml 

<properties>
            <property name="openjpa.ConnectionDriverName" 
                value="org.apache.derby.jdbc.EmbeddedDriver"/>
      <property name="openjpa.ConnectionURL" 
                value="jdbc:derby:C:/Users/tr1t6321/ipeks"/>
            <property name="openjpa.ConnectionUserName"  value=""/>
            <property name="openjpa.ConnectionPassword" value=""/>
            <property name="openjpa.Log" value="DefaultLevel=TRACE"/>
        </properties>

!!! persistence.xml should be in src/META-INF.


......Inheritance.....
1.  @Table(name="CUSTOMER")
@Entity(name = "CUSTOMER") //Name of the entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="CUST_TYPE", discriminatorType=DiscriminatorType.STRING,length=10)
@DiscriminatorValue("RETAIL")

2. @Table(name="CUSTOMER")
@Entity(name = "CUSTOMERJOINED") //Name of the entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="CUST_TYPE", discriminatorType=DiscriminatorType.STRING,length=10)
@DiscriminatorValue("RETAIL")

3. @Table(name="CUSTOMER")
@Entity(name = "CUSTOMERTABLE") //Name of the entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

Let's insert some customer....

public static void main(String[] args) {
EntityManagerFactory entityManagerFactory =  Persistence.createEntityManagerFactory("testjpa");

EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();

userTransaction.begin();
//inserting Customer
Customer customer = new Customer();
customer.setFirstName("Charles");
customer.setLastName("Dickens");
customer.setCustType("RETAIL");
customer.getAddress().setStreet("10 Downing Street");
customer.getAddress().setAppt("1");
customer.getAddress().setCity("NewYork");
customer.getAddress().setZipCode("12345");
em.persist(customer);
userTransaction.commit();

OpenJPAEntityManager oem = OpenJPAPersistence.cast(em);
Object objId = oem.getObjectId(customer);
Customer cust = em.find(Customer.class, objId);

em.close();
entityManagerFactory.close();
System.out.println("Customer info: " + cust);

}


Some crucial points:
!!! While running your java project with openjpa; put the following argument to
Run > Run configurations> arguments
VM box: -javaagent:D:/apache-openjpa-2.3.0/openjpa-2.3.0.jar

Hiç yorum yok:

Yorum Gönder