Thursday, 31 March 2011

Tools for converting c to java source

There are tools which provides opportunity to translate C-code sources into Java classes. Some of them are listed below:
  • Jazillian: Jazillian is a tool that translates from C source code to Java source code. The Java code that it produces is highly maintainable: it looks like hand-written code.
  • C to Java converter: Some time ago I needed to convert one C program to Java. It is tedious and not interesting job to do. So I developed C to Java converter. I can not say, that it is fully functional or have no bugs. But you may find it useful to use this tool first, before making changes by hand.
  • C2J converter: C2J converter provides opportunity to translate C-code sources into Java classes.

Conversion from decimal to binary

You can convert a decimal to binary using toBinaryString() method of Integer wrapper class as follows.

int i = 42;
String binstr = Integer.toBinaryString(i);

Conversion from integer to hexadecimal and vice-versa

You can convert a hexadecimal to integer using two different methods as shown below:
int i = Integer.valueOf("B8DA3"16).intValue();

   or

int i = Integer.parseInt("B8DA3"16);  


You can convert a decimal to binary using three different methods as shown below:

int i = 42;
String hexstr = Integer.toString(i, 16);

or

String hexstr = Integer.toHexString(i);

or (with leading zeroes and uppercase)

public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}

Covariant Parameter Types

Read - What is covariance?
Covariant Return type

Now we have a look at covariant method parameters, which are considered unsound.


Consider the following code:
public interface TestInterface { }

public class TestClass implements TestInterface { }

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

public class Test {
private List<testclass> list;

public TestInterface test() {
list = new ArrayList<testclass>();
list.add(new TestClass());

return covariant(list);
}

public TestInterface covariant(List<testinterface> ilist) {
return ilist.remove(0);
}
}

Now there is absolutely no reason why this should not work. It is trivially inferable that the above code treats ilist as covariant in the list-type - and that therefore this code is statically correct.

Of course Java's typing has never been particularly smart. List.add(T1) is contra-variant in t1, and T2 List.get(int) is co-variant in t2; so the Java compiler is correct to infer that in the general case List and List are substitutable iff t1 == t2.

If we can't declare a generic parameter to be covariant in its type parameter we have a serious problem - it means that any non-trivial algorithm involving collections is going to run afoul of this. You might consider trying to cast your way around it:


public TestInterface test() {
list = new ArrayList<testclass>();
list.add(new TestClass());

return covariant((List<testinterface>)list);
}

but not surprisingly that didn't work.

Test.java:11: inconvertible types
found : java.util.List<testclass>
required: java.util.List<testinterface>
return convariant((List<testinterface>)list);
^
1 error

If you continue to hack at it you might try a double cast via a non-generic List.

public TestInterface test() {
list = new ArrayList<testclass>();
list.add(new TestClass());

return covariant((List<testinterface>)((List)list));
}

This works but leaves us with the unchecked/unsafe operation warning:
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.



Now this is a perfectly reasonable warning - it is unchecked; it is unsafe; and more importantly it does violate encapsulation. The problem here is that the caller should not be defining the type invariants of the callee - that's the job of the method signature!

The correct solution is to allow us to declare covariant() to be covariant in its argument; and fortunately Java does support this.

To declare an argument to be covariant in its type parameter you can use the extends keyword:
public TestInterface covariant(List<? extends TestInterface> ilist) {
return ilist.remove(0);
}

To declare an argument to be contravariant in its type parameter you use the super keyword:
public void contravariant(List<? super TestClass> clist, TestClass c) {
clist.add(c);
}



Saturday, 26 March 2011

JPA : Persistence unit

The EntityManager is created by the EntitiyManagerFactory which is configured by the persistence unit. The persistence unit is described via the file "persistence.xml" in the directory META-INF in the source folder. A set of entities which are logical connected will be grouped via a persistence unit. "persistence.xml" defines the connection data to the database, e.g. the driver, the user and the password,

JPA 2.0 with EclipseLink

This tutorial explains how to use EclipseLink, the reference implementation for the Java Persistence API (JPA). The usage of EclipseLink is demonstrated for stand-aloneJava applications (outside the Java EE environment). The JPA 2.0 implementation was used for this tutorial.

Table of Contents 

JPA

JPA resoures for eclipse link

http://www.eclipse.org/eclipselink/ EclipseLink
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/persistenceapi/ Using the Java Persistence API in Desktop Applications
http://www.ibm.com/developerworks/java/library/j-typesafejpa/index.html Dynamic, typesafe queries in JPA 2.0 using the Criteria API

JPA : Relationship Example using eclipse link

Create a Java project "com.vaani.jpa.eclipselink", create again a folder "lib" and place the required JPA jars and derby.jar into this folder. Add the libs to the project classpath.
Create the package "com.vaani.jpa.eclipselink.model" and the following classes.
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Family {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private String description;

@OneToMany(mappedBy = "family")
private final List<Person> members = new ArrayList<Person>();

public int getId() {
return id;
}

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

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

public List<Person> getMembers() {
return members;
}

}


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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private String id;
private String firstName;
private String lastName;

private Family family;

private String nonsenseField = "";

private List<Job> jobList = new ArrayList<Job>();

public String getId() {
return id;
}

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

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

// Leave the standard column name of the table
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

@ManyToOne
public Family getFamily() {
return family;
}

public void setFamily(Family family) {
this.family = family;
}

@Transient
public String getNonsenseField() {
return nonsenseField;
}

public void setNonsenseField(String nonsenseField) {
this.nonsenseField = nonsenseField;
}

@OneToMany
public List<Job> getJobList() {
return this.jobList;
}

public void setJobList(List<Job> nickName) {
this.jobList = nickName;
}

}


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Job {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private double salery;
private String jobDescr;

public int getId() {
return id;
}

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

public double getSalery() {
return salery;
}

public void setSalery(double salery) {
this.salery = salery;
}

public String getJobDescr() {
return jobDescr;
}

public void setJobDescr(String jobDescr) {
this.jobDescr = jobDescr;
}

}


Create the file "persistence.xml" in "src/META-INF". Remember to change the path to the database.

<?xml version="1.0" encoding="UTF-8" ?>
<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_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="people" transaction-type="RESOURCE_LOCAL">


<class>com.vaani.jpa.eclipselink.model.Person</class>
<class>com.vaani.jpa.eclipselink.model.Family</class><class>com.vaani.jpa.eclipselink.model.Job</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/relationsshipDb;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />

<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>

</persistence-unit>
</persistence>


The following check is implemented as a JUnit Test. The setup() method will create a few test entries. After the test entries are created, they will be read and the one field of the entries is changed and saved to the database.

import static org.junit.Assert.assertTrue;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.junit.Before;
import org.junit.Test;

import com.vaani.jpa.eclipselink.model.Family;
import com.vaani.jpa.eclipselink.model.Person;

public class JpaTest {

private static final String PERSISTENCE_UNIT_NAME = "people";
private EntityManagerFactory factory;

@Before
public void setUp() throws Exception {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();

// Begin a new local transaction so that we can persist a new entity
em.getTransaction().begin();

// Read the existing entries
Query q = em.createQuery("select m from Person m");
// Persons should be empty

// Do we have entries?
boolean createNewEntries = (q.getResultList().size() == 0);

// No, so lets create new entries
if (createNewEntries) {
assertTrue(q.getResultList().size() == 0);
Family family = new Family();
family.setDescription("Family for the Knopfs");
em.persist(family);
for (int i = 0; i < 40; i++) {
Person person = new Person();
person.setFirstName("Jim_" + i);
person.setLastName("Knopf_" + i);
em.persist(person);
// First we have to persists the job
// Now persists the new person
family.getMembers().add(person);
em.persist(person);
em.persist(family);
}
}

// Commit the transaction, which will cause the entity to
// be stored in the database
em.getTransaction().commit();

// It is always good practice to close the EntityManager so that
// resources are conserved.
em.close();

}

@Test
public void checkAvailablePeople() {

// Now lets check the database and see if the created entries are there
// Create a fresh, new EntityManager
EntityManager em = factory.createEntityManager();

// Perform a simple query for all the Message entities
Query q = em.createQuery("select m from Person m");

// We should have 40 Persons in the database
assertTrue(q.getResultList().size() == 40);

em.close();
}

@Test
public void checkFamily() {
EntityManager em = factory.createEntityManager();
// Go through each of the entities and print out each of their
// messages, as well as the date on which it was created
Query q = em.createQuery("select f from Family f");

// We should have one family with 40 persons
assertTrue(q.getResultList().size() == 1);
assertTrue(((Family) q.getSingleResult()).getMembers().size() == 40);
em.close();
}

@Test(expected = javax.persistence.NoResultException.class)
public void deletePerson() {
EntityManager em = factory.createEntityManager();
// Begin a new local transaction so that we can persist a new entity
em.getTransaction().begin();
Query q = em
.createQuery("SELECT p FROM Person p WHERE p.firstName = :firstName AND p.lastName = :lastName");
q.setParameter("firstName", "Jim_1");
q.setParameter("lastName", "Knopf_!");
Person user = (Person) q.getSingleResult();
em.remove(user);
em.getTransaction().commit();
Person person = (Person) q.getSingleResult();
// Begin a new local transaction so that we can persist a new entity

em.close();
}
}

Simple example on JPA with eclipse link

Create a Java project "com.vaani.jpa.simple". Create a folder "lib" and place the required JPA jars and derby.jar into this folder. Add the libs to the project classpath.
Afterwards create the package "com.vaani.jpa.simple.model" and create the following classes.
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String summary;
private String description;

public String getSummary() {
return summary;
}

public void setSummary(String summary) {
this.summary = summary;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

@Override
public String toString() {
return "Todo [summary=" + summary + ", description=" + description
+ "]";
}

}


Persistence Unit

Create a directory "META-INF" in your "src" folder and create the file "persistence.xml". This examples uses EclipseLink specific flags for example via the parameter "eclipselink.ddl-generation" you specify that the database scheme will be automatically dropped and created.

<?xml version="1.0" encoding="UTF-8" ?>
<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_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="todos" transaction-type="RESOURCE_LOCAL">
<class>com.vaani.jpa.simple.model.Todo</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />

<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>

</persistence-unit>
</persistence>





The database specified via "javax.persistence.jdbc.url" will be automatically created by the Derby Driver. You may want to adjust the path, it currently is based on Linux notations and points to my home directory on my Linux system.

To see the SQL generated for the the databases set eclipselink.ddl-generation.output-mode value from "database" to "sql-script" or "both". Two files will get generated 'createDDL.jdbc' and 'dropDDL.jdbc'

Test your installation

Create the following Main class which will create a new entry every time it it called. After the first call you need to remove the property "eclipselink.ddl-generation" from persistence.xml otherwise you will receive an error as EclipseLink tries to create the database scheme again. Alternative you could set the property to "drop-and-create-tables" but this would drop your database schema at every run.

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.vaani.jpa.simple.model.Todo;

public class Main {
private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;

public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("select t from Todo t");
List<Todo> todoList = q.getResultList();
for (Todo todo : todoList) {
System.out.println(todo);
}
System.out.println("Size: " + todoList.size());

// Create new todo
em.getTransaction().begin();
Todo todo = new Todo();
todo.setSummary("This is a test");
todo.setDescription("This is a test");
em.persist(todo);
em.getTransaction().commit();

em.close();
}
}


Run you program several times to see that the database is filled.

Installation - Eclipse link and derby for JPA

EclipseLink

Download the EclipseLink implementation from http://www.eclipse.org/eclipselink/downloads/ . The download contains several jars. We need the following jars:
  • eclipselink.jar
  • javax.persistence_2.0.X.jar

Derby Database

The example later will be using Apache Derby as a database. Download Derby from http://db.apache.org/derby/ From this tutorial we will need the "derby.jar". For details on Derby (which is not required for this tutorial) please see Apache Derby .

Relationship Mapping

JPA allows to define relationships between classes, e.g. it can be defined that a class is part of another class (containment). Classes can have one to one, one to many, many to one, and many to many relationships with other classes.
A relationship can be bidirectional or unidirectional, e.g. in a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class. Within a bidirectional relationship you need to specify the owning side of this relationship in the other class with the attribute "mappedBy", e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass".



 
Relationship annotations
@OneToOne
@OneToMany
@ManyToOne
@ManyToMany

Persistence of fields

The fields of the Entity will be saved in the database. JPA can use either your instance variables (fields) or the corresponding getters and setters to access the fields. You are not allowed to mix both methods. If you want to use the setter and getter methods the Java class must follow the Java Bean naming conventions. JPA persists per default all fields of an Entity, if fields should not be saved they must be marked with @Transient.
By default each field is mapped to a column with the name of the field. You can change the default name via @Column(name="newColumnName").
The following annotations can be used.

 
Annotations for fields / getter and setter
@Id Identifies the unique ID of the database entry
@GeneratedValue Together with ID defines that this value is generated automatically.
@Transient Field will not be saved in database

Friday, 25 March 2011

Entities and Transactions in JPA

All entities have the property of transactionability and their CRUD operations will take place within a transactional context. Transactions can be broadly classified into two types based on who actually owns (or manages) the transaction. They are JTA and Resource-local transaction.

In the case of a J2EE Application, the default transaction type is JTA (Java Transaction API), unless explicitly specified. A method can be simply annotated with @RequiresNew (or @Requires) in which case a new transaction will always started by the container and the transaction completes as soon as the method ends.

Whereas in a J2SE application, the transaction-type defaults to Resource-local, which means that the developer (or the application code) has to explicitly start and end a transaction. It means that the user has to explicitly start a transaction with the help of EntityManager object, and then have to commit it, if everything goes normal, else have to roll-back the transaction if some error occurs.

The following code shows this,

EntityTransaction userTransaction = entityManager.getTransaction();
try{
userTransaction.begin();

// Do something here.

// If everthing goes well, make a commit here.
userTransaction.commit();
}catch(Exception exception){
// Exception has occurred, roll-back the transaction.
userTransaction.rollback();
}


Operations on Entity Objects


The following are the legal operations that can be performed on Entity objects with the help of EntityManager API. As seen previously, EntityManager are objects that manage one or more entity objects with the help of an implicit persistence context.

Persisting Entity Objects:
Entity objects are like regular java objects until they become managed and made persistent by the EntityManager. The following piece of code makes an entity to become persistent and managed.

MobileEntity mobileObject = new MobileEntity();
mobileObject.set()... // Update the state values here.
entityManager.persist(mobileObject);


The persist(entityObject) methods makes the entity persistent in the underlying database and managed within the persistence context of the EntityManager, whether the persistence context is a transaction-scoped or an extended persistence context depends upon how actually the EntityManager was configured.

[What happens when a managed entity is again forced to become managed by calling the persist() method. Or what happens when the persist() method is called couple of times on the same entity object.

Whenever the persist() method is called, the persistence engine will check for the existence of that object with the help of its unique identifier (which is represented in the form of primary key). If any duplicate object is found, then a run-time exception, EntityExistsException will be thrown.]

Querying for Entities:
Developers can either depend on the EntityManager for simple search or Query objects for providing powerful search conditions for locating and querying entity objects.

Using EntityManager object:
Following are the two different methods available in EntityManager interface for querying entity objects and there are some major differences between the two.

Using the EntityManager.find() method:
The find() method takes the class name of the Entity object and the primary key value for locating a single entity object. If the object of interest cannot be located by the EntityManager, then this method will simply return null. The following code illustrates this,

MobileEntity mobile = entityManager.find(MobileEntity.class, “ABC-123”);
If (mobile != null){ // mobile object may or may not be null.
// Process the object.
}


One good thing about the find() method is that, the returned entity object soon becomes managed automatically within the persistence context of the EntityManager.

Using the EntityManager.getReference() method:
This method, like the EntityManager.find() method, takes the name of the entity class and the primary key as their arguments. But the difference is, unlike the find() method which will return null if the entity object is not found, this method will throw an exception EntityNotFFoundException. Another difference between this method and the find() method is that, the entity that is fetched by this method may be lazily loaded. That is, the state of the state of entity (like model, manufacturer, imeiNo may be lazily loaded during the first time it is actually accessed).

MobileEntity mobile = entityManager.getReference(MobileEntity.class, “ABC-123”);
// mobile object may not contain the actual state values for model, manufacturer
// and imei number, the states may be loaded during the first access.

String model = mobile.getModel();
// The persistence engine may fetch the model value for the mobile here
// at this particular point of time.
…..


Using the Query object: Discussed later.

Deleting Entities:
To remove (delete) an entity object from the database, make a call to EntityManager.remove(entityObject) method. The entity object that is passed to the remove() must be a managed entity, else the operation will fail.

Also, making this call may or may-not remove the entity immediately from the database. The algorithm that achieves the same is implementation specific. Some implementation may only mark the entity as a removed entity after this method call, and the actual deletion of the entity object in the database may happen when a flush() operation (which is discussed later) is made.

After this method call, the entity will become detached from the persistence context and it is no longer a managed one.

Updating Entities:
The EntityManager.merge(entityObject) method will make a detached entity to get associated with the current persistence context of the EntityManager. Consider the following lines of code.

// Transaction has begin.
…..
MobileEntity mobile = entityManager.find(MobileEntity.class, “ABC-123”);
…..
// Transaction ends.

mobile.set()…… // Updating the mobile object.

entityManager.merge(mobile);


In the above piece of code, a mobile entity object is located with the EntityManager.find() method. This entity is now in a managed state. Assume that the transaction ends after some point of time and also the persistence context is a transaction-scoped persistence context. As soon as the transaction completes, the persistence context will go off, (since the persistence context is a transaction-scoped persistence context). So the entity object becomes detached from the persistence context. After this any modifications that are made to the mobile object won’t be knowledgeable to the EntityManager as the mobile object has already been detached from it.

Now, calling the merge() method, will make the mobile object becomes managed, and all the recent changes that are made to it will become visible to the current persistence context of the EntityManager.

Flushing and Refreshing:

The EntityManager.flush() will synchronize all the changes that are made to the persistent entities back to the underlying database, whereas the EntityManager.refresh() does the reverse. It will update the entity object with values taken from the database. Any new values that are set to the entity objects will be lost as a result of this method call.

For example, consider the following piece of code,

MobileEntity mobile = …..
mobile.set(); // Update the state values for the mobile object.
….
entityManager.flush();
// Calling this flush method will synchronize the database with the values
// taken from the entity object.
consider this code,


MobileEntity mobile = …
mobile.set(); // The state values for the mobile object is updated.
…..
entityManager.refresh();
// The refresh() method will refresh the entity object with the values taken from the database.
// All the updates that are done are lost.


EntityManager in JPA

This class follows the standard Manager Design pattern for managing entities. Managing an entity or a set of entities refers to the act of bring a set of Java objects under the control of EntityManager. Unless entities don’t have any explicit association with EntityManager they are just ordinary java objects (though their corresponding classes have been marked with @Entity annotation).

This EntityManager API provides services for persisting an entity, removing an entity, querying and deleting entities.

In a J2SE application, a reference to an entity manager (EntityManager) can be obtained using the entity manager factory (EntityManagerFactory) and the Persistence class. The persistence class is a helper class (or a bootstrap) used to create EntityManagerFactory objects. With EntityManagerFactory objects, references to EntityManager objects can be obtained. The following code illustrates the same,

EntityManagerFactory entityManagerFactory =  Persistence.createEntityManagerFactory(“PersistentUnitName”);
EntityManager eManager = entityManagerFactory.createEntityManager();


[An EntityManagerFactory can be configured with some set of properties with the help of Persistent Units. Notice that one of the arguments to createEntityManagerFactory() is the name of the persistent unit which is discussed in the later sections.]

In a J2EE application, the container will directly inject a reference to the EntityManager using dependency injection, so the code becomes as simple like this,

@Resource
private EntityManager entityManager;


Persistence Context


To be very precise, a persistent context manages a set of entities which in turn is managed by the EntityManager. A persistent context keeps track of the state (or the changes) that an entity object may undergo. And the EntityManager takes the support of this persistence context to commit or to undo the changes. As soon as an EntityManager object is created, it is implicitly associated with a persistence context for managing a set of entities.

Persistent Context comes in two flavors, one is the transaction-scoped persistent context and the other one is extended persistent context.

Transaction-Scoped Persistence Context: Imagine that a set of entities are managed by the persistence context. At this time, we say that the entities are bound to (or attached) to the persistent context. Changes may happen to these entities and these changes will occur within a transaction. Sometimes later when the transaction ends (commits or roll-back), the entities will unbind (detached) from the persistent context. As soon as the entities are detached from the persistence context, they are no longer being managed. Any changes that happen to these entities will not be persisted as they don’t have any association with the persistence context. Such kind of persistent context whose life-time is dependent on the life-time of the transaction (for a set of entities at that particular point of time) is termed as transaction-scoped persistent context.

All the transaction-scoped persistence context are configured by injecting @PersistentContext to EntityManager objects , like this,

@PersistenceContext(name=”PersistentUnitName”)
private EntityManager entityManager;


[Note: There is no such public interface called PersitenceContext in the Java Persistence API. The EntityManager may implicitly depend on a virtual Persistence Context class for managing the entities. So, creating a transaction-scoped persistence context is nothing but creating an EntityManager object that has been configured with @PersistenceContext annotation.]

Extended Persistence Context: Unlike transaction-scoped persistence context, where the life-time of the persistence context will end as soon the transaction is completed, a persistence context may be configured to live even after a transaction completes. In such a case, all the entities that are managed by such a persistence context will still be in a manageable state only even after the transaction ends. They won’t be detached from the context. Such long-lived persistence context that will continue to exist even after the completion of a transaction is called extended persistence context.

All the extended persistence context objects are created and managed manually by the application code only (that is by the developers).

[As soon as an EntityManager object is created, an implicit Persistence context will be associated with it and it is soon kept open and prepared for managing a set of entities, meaning that the calling EntityManager.isOpen() method will always return true. Calling the EntityManager.clear() method will clear the current persistence context associated with the EntityManager and all the entities that have their associations will now be cleared and they become detached from the EntityManager. To release all the resources referenced by the EntityManager, call the close() method, After this method call, calling any of the methods will throw IllegalStateException.]

Customizing the Entity object in JPA

Changing the default table name

By default the table name corresponds to the unqualified name of the class. We can change this behavior with the help of @Entity annotation itself, like this.


@Entity(name = "MOBILE_ENTITY")
public class MobileEntity{
……
}


Now, the table name becomes MOBILE_ENTITY and this should be the name that must be referred in query strings (Queries are discussed later). The value to the name property must be legal in the sense, it cannot accept any keywords that are found in the query language.


Customizing the Column behaviors


The default name of the columns, their size, whether they can accept null values or not etc., can be customized using the @Column annotation. Following is the sample code that illustrates this,


@Column(name = “MOBILE_MODEL”, nullable = true, length = 35)
private String model;

@Column(name = “MOBILE_MANUFACTURER” nullable = true, length = 100)
private String manufacturer;

@Id
@Column(name = “MOBILE_IMEI_NO”, nullable = false)
private String imeiNo;

 

The name property, when specified will override the default column name (which is the same as that of the field name in the Entity class). The nullable property tells that whether the column can accept null values. Length property is only applicable if the type of the column is String (or VARCHAR). There are also properties like scale and precision which is applicable only when the type of the column is NUMBER.

[Note, multiple annotations can be legally applied to elements (like class, field, method etc.). In the above example the imeiNo has two annotations attached with it, namely @Id and @Column.]

Auto-generation of Primary Keys


A primary key for an entity which is usually annotated with @Id annotation can be given a value manually or we can depend on the persistence provider for the same. For this we have to use the @GeneratedValue annotation.

Consider the following example,

    @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String imeiNo;





Since the imeiNo is going to be the primary key for the mobile object, we have decorated the field with @GeneratedValue annotation, which delegates the burden of creating values from developers to the persistence engine. Also, there are 4 different methods (or strategies) for primary key generation, which are AUTO, IDENTITY, SEQUENCE and TABLE. The simplest one is the automatic primary key generation strategy which is represented as GenerationType.AUTO.

[GenerationType is an Enumeration (new feature in Java 5.0) and the four different strategies for primary key generation, namely AUTO, IDENTITY, TABLE and SEQUENCE are defined in that enumeration.]

Thursday, 24 March 2011

JPA Architecture

Java Persistence API or JPA for short is a lightweight, POJO-based Java framework to persist the Java Objects to the relational database. JPA is uses metadata to map the persistence objects with the database table. JPA supports SQL like query language to ease the process of querying the database. JPA Query language can be used to execute both static and dynamic queries.

JPA supports many ORM frameworks available these days. You can use either free or commercial ORM framework in your JPA based applications. It's also very easy to switch to different ORM frameworks.

List of ORM frameworks:

  1. Hibernate
  2. Toplink from oracle
  3. iBatis
  4. Open JPA

You can easily plug any persistence provider into your JPA application.

JPA Concepts

JPA concept includes the three components Entity, EntityManager and EntityManagerFactory. Following diagram shows the primary components of JPA architecture.

Entity

Entity is the persistence (POJO) objects that represent one record in the table. The Entity is simple annoted POJO class, which is easy to develop. Here are the characteristics of an Entity:

  1. Entity can be persisted to the relational database
  2. Entity is identified by persistence identity (the primary key of the table)
  3. Entity supports transactions
  4. Entity supports inheritance

Example consider this class:

class MobileEntity{

private String model;
private String manufacturer;
private Double price;
private String imeiNo;

…..
// Getters and Setters go here.
}


Now to make it an entity, we mark the class with @Entity annotation:


@Entity
class MobileEntity{

private String model;
private String manufacturer;
private Double price;
private String imeiNo;

…..
// Getters and Setters go here.
}


EntityManager

The EntityManager interface is providing the API for interacting with the Entity. Some of the functions provided by EntityManager API are:


  1. persist – this method is used to save a new entity
  2. merge – this method is used to update the sate of entity into database
  3. remove – this method is used to remove the entity instance

You will learn about all these functions in next sections. We have developed many JPA examples to help you in learning JPA.

EntityManagerFactory

The EntityManagerFactory is used to create an instance of EntityManager. In your application when there is no use of EntityManagerFactory or application shuts down then it is necessary to close the instance of EntityManagerFactory . Once the EntityManagerFactory is closed, all its EntityManagers are also closed.

JDBC vs ORM

Since entities form the heart of the JPA, they have some unique characteristics like persistability, identity and transactionability. The property of persistability deals with the storing and retrieving of entity from and to a persistent medium like database. Identity property is usually used to identity one unique entity among multiple entities (or multiple entity instances) in a database. All the CRUD operations (Create, Update and Delete) for entity objects will occur within a transactional context and it is one of the major characteristic for an entity object as the real state of an entity depends whether a transaction completes (commits/fails) or not.

Example

import  java.sql.*;

public class AllTableName{
public static void main(String[] args) {
System.out.println( "Listing all table name in Database!" );
Connection con = null ;
String url = "jdbc:mysql://localhost:3306/" ;
String db = "jdbctutorial" ;
String driver = "com.mysql.jdbc.Driver" ;
String user = "root" ;
String pass = "root" ;
try {
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
try {
DatabaseMetaData dbm = con.getMetaData();
String[] types = { "TABLE" };
ResultSet rs = dbm.getTables(null,null, "%" ,types);
System.out.println( "Table name:" );
while (rs.next()){
String table = rs.getString( "TABLE_NAME" );
System.out.println(table);
con.close();
}
}
catch (SQLException s){
System.out.println( "No any table in the database" );
}
}
catch (Exception e){
e.printStackTrace();
}
}
}


Above program retrieves the names of all tables present in the database and then displays on the console.

Advantages of JDBC


  • Clean and easily for small programs
  • JDBC provides good performance with large amount of data
  • Small JDBC programs can be developed very easily
  • Very good for small applications

Disadvantages of JDBC


  • JDBC is not easily if it is used in large projects. There is a big programming overhead.
  • Programmer must hardcode the Transactions and concurrency code in the application.
  • Handling the JDBC connections and properly closing the connection is also a big issue. Properly closing the connection is must.
  • JDBC is not good for big applications

ORM


ORM stands for Object Relational Mapping, is another technology to access the data databases. Here business object is directly mapped to the database tables with the help of ORM framework.

ere are the benefits of ORM technology


  • No need to deal with the SQL Queries to save and retrieve the data
  • Simple configuration
  • Standardized API to persist the business objects
  • Fast development of application
  • Concurrency support
  • Excellent cashing support for better performance of the application
  • Injected transaction management
  • Configurable logging
  • Easy to learn and use

Disadvantages of ORM


  • Slow performance in case of large batch updates
  • Little slower than JDBC 

JPA : Overview

The Java Persistence API or JPA is one to the specification of JEE5, which allows the programmer to develop the persistence layer for their desktop and web applications. JPA is developed to ease the development of persistence layer and it has also standardized the Java ORM or Object Relational Mapping technologies.

It provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications.

Persistence Entities

Persistent Data normally refers to permanent data in an application. The state of these data is made permanent by storing them in a persistent medium like database, files or a disk tape. In JPA terms, these persistent data are referred as entities. An entity refers to a logical collection of data that can be stored or retrieved as a whole. For example, in a banking application, Customer and BankAccount can be treated as entities. Customer name, customer address etc can be logically grouped together for representing a Customer entity. Similarly account number, total balance etc may be logically grouped under BankAccount entity.

Since entities form the heart of the JPA, they have some unique characteristics like persistability, identity and transactionability. The property of persistability deals with the storing and retrieving of entity from and to a persistent medium like database. Identity property is usually used to identity one unique entity among multiple entities (or multiple entity instances) in a database. All the CRUD operations (Create, Update and Delete) for entity objects will occur within a transactional context and it is one of the major characteristic for an entity object as the real state of an entity depends whether a transaction completes (commits/fails) or not.

Initialling to zero rather than null

Some classes like BigDecimal,String have empty element into it. So we should use them nicely. Initialize these to zero, rather than null.

public void someFunc(BigDecimal p_number)
{
BigDecimal m_number;
m_number = p_number==null?BigDecimal.Zero : p_number;
}

Equivalent of function pointers of C in java

Function pointers were omitted from the Java programming language because object references can be used to provide the same functionality. Invoking a method on an object typically performs some operation on that object. However, it is possible to define an object whose methods perform operations on other objects, passed explicitly to the methods.
An instance of a class that exports exactly one such method is effectively a pointer to that method. Such instances are known as function objects. For example, consider the following class:

class StringLengthComparator {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}


This class exports a single method that takes two strings and returns a negative integer if the first string is shorter than the second, zero if the two strings are of equal length, and a positive integer if the first string is longer. This method is a comparator that orders strings based on their length instead of the more typical lexicographic ordering. A reference to a StringLengthComparator object serves as a “function pointer” to this comparator,
allowing it to be invoked on arbitrary pairs of strings. In other words, a StringLengthComparator instance is a concrete strategy for string comparison.
As is typical for concrete strategy classes, the StringLengthComparator class is stateless: It has no fields, hence all instances of the class are functionally equivalent to one another. Thus it could just as well be a singleton to save on unnecessary object creation costs :
class StringLengthComparator {
private StringLengthComparator() { }
public static final StringLengthComparator
INSTANCE = new StringLengthComparator();
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}

To pass a StringLengthComparator instance to a method, we need an appropriate type for the parameter. It would do no good to use StringLengthComparator because clients would be unable to pass any other comparison strategy. Instead, we need to define a Comparator interface and modify StringLengthComparator to implement this interface. In other words, we need to define a strategy interface to go with the concrete strategy class. Here it is:
// Strategy interface
public interface Comparator {
public int compare(Object o1, Object o2);
}

Get file size in java

How to check the file size:
public static long getFileSize(String filename) {

File file = new File(filename);

if (!file.exists() || !file.isFile()) {
System.out.println("File doesn\'t exist");
return -1;
}

//Here we get the actual size
return file.length();
}

To get the file size in KB, just divide file.length() by 1024. i.e.


public static long getFileSizeInKB(String filename) {
File file = new File(filename);
if (!file.exists() || !file.isFile()) {
System.out.println("File doesn\'t exist");
return -1;
}
//Here we get the size in KB
return file.length()/1024;
}

Monday, 21 March 2011

More on XML serialization with JAXB

I posted some days ago an article explaining how to “XML-serialize” objects with JAXB in Eclipse. The downside of using XSD for XML serialization is the dependency on the XML schema that will generate java classes; this is because I wanted to extend the classes to have extra-functionality, more constructors and so on. So I started looking for a way to serialize objects to XML without creating XSD definitions… but I found a problem: every time java classes are generated, an additional class, called ObjectFactory.java is also created. It is also needed for XML marshalling/unmarshalling. The only viable solution I found was to write my one ObjectFactory.java class, to be used by JAXB when serializing objects.

But I creating ObjectFactory is not necessary. We can simply serialize from simple xml files(see here).

But if we want we can create our own ObjectFactory Class. Example:

Step 1: Create the java classes that you need. In my case, I had two main entities, Node and Line, and two additional collections, Lines and Nodes. I also created a Graph entity, holding a list with nodes and a list with lines. Below are presented Line.java, Lines.java and Graph.java files

Line.java

package com.vaani.jaxb.objects;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Line", propOrder = { "startNode", "endNode" })
public class Line {

@XmlAttribute(name = "StartNode")
protected int startNode;
@XmlAttribute(name = "EndNode")
protected int endNode;

public Line(int start, int end) {
this.setStartNode(start);
this.setEndNode(end);
}

public Line() {
this(0, 0);
}

public int getStartNode() {
return startNode;
}

public void setStartNode(int value) {
this.startNode = value;
}

public int getEndNode() {
return endNode;
}

public void setEndNode(int value) {
this.endNode = value;
}

}


Lines.java

package com.vaani.jaxb.objects;

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "lines", propOrder = { "lines" })
public class Lines {

@XmlElement(name = "Line")
protected List<Line> lines;

public List<Line> getLines() {
if (lines == null) {
lines = new ArrayList<Line>();
}
return this.lines;
}
}



Graph.java

package com.vaani.jaxb.objects;

import java.io.*;
import java.util.*;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Graph")
public class Graph {

@XmlElement(name = "Nodes", required = true)
protected Nodes nodes = new Nodes();
@XmlElement(name = "Lines", required = true)
protected Lines lines = new Lines();
@XmlAttribute(name = "StartNode")
protected int startNode;
@XmlAttribute(name = "EndNode")
protected int endNode;

public void addNode(int x, int y) {
getNodes().add(new Node(x, y, getNodes().size() + 1));
}

public void addLine(int start, int end) {
getLines().add(new Line(start, end));
}

public List<Node> getNodes() {
return nodes.getNodes();
}

public void setNodes(Nodes value) {
this.nodes = value;
}

public List<Line> getLines() {
return lines.getLines();
}

public void setLines(Lines value) {
this.lines = value;
}

public int getStartNode() {
return startNode;
}

public void setStartNode(int value) {
this.startNode = value;
}

public int getEndNode() {
return endNode;
}

public void setEndNode(int value) {
this.endNode = value;
}

public void marshalToFile(String fileName) {
try {
JAXBContext jc = JAXBContext.newInstance(this.getClass().getPackage().getName());
Marshaller m = jc.createMarshaller();
m.marshal( this, new FileOutputStream(fileName) );
} catch(Exception e) {
e.printStackTrace();
}
}

public static Graph unmarshalFromFile(String fileName) {
try {
JAXBContext jc = JAXBContext.newInstance((new Graph()).getClass().getPackage().getName());
Unmarshaller um = jc.createUnmarshaller();
return (Graph) um.unmarshal(new File(fileName));
} catch (Exception e) {
return new Graph();
}
}


}


In order to be able to serialize the above classes, we must use the XML annotations like @XmlRootElement, @XmlElement, @XmlAttribute, @XmlType. For the serialization, we use the same JAXBContext, Marshaller and Unmarshaller classes.

Step 2: Implement the ObjectFactory.java class

package com.vaani.jaxb.objects;

import javax.xml.bind.annotation.XmlRegistry;

@XmlRegistry
public class ObjectFactory {

public ObjectFactory() {
}

public Graph createGraph() {
return new Graph();
}

public Node createNode() {
return new Node();
}

public Line createLine() {
return new Line();
}

}


As you can see, the class must be preceded by @XmlRegistry annotation.

Step 3: Test the serialization

package com.vaani.jaxb.objects;

import org.junit.*;
import static org.junit.Assert.*;

public class GraphTest {

Graph graph;

@Test
public void test_graph()
{
createGraph();
graph.marshalToFile("newGraphOutput.xml");
Graph secondGraph = Graph.unmarshalFromFile("newGraphOutput.xml");
assertTrue(secondGraph.getLines().size() == 2);
assertTrue(secondGraph.getNodes().size() == 3);
}

private void createGraph()
{
graph = new Graph();
graph.addNode(60, 60);
graph.addNode(110, 110);
graph.addNode(60, 110);
graph.addLine(1, 3);
graph.addLine(2, 3);
}
}


Step 4: Check the result

image