Suggested Pages

Tuesday, July 31, 2012

Transaction Commit and Transaction Rollback

A transaction has only two ways to end: commit or rollback. If you don't commit or rolls back explicitly, the transaction remains alive and it may holds locks (exclusive lock).
Then when the connection is closed by the client, the transaction will commit or roll back depending on how the vendor implements the JDBC specification that doen't say nothing about it.
For example Oracle driver commits on closed connection.

JPA Persistence context as First Level Cache


The Persistence Context is a set of entities in the Managed State. Entities in Persistence Context have a unique persistent identity and these entities are used to synchronize objects in memory with objects in the database.
In this post we'll see how the Persistence Context acts like a first level cache.

Code Example


GenericDAO.java
....

@Repository
public class GenericDAO {

 @PersistenceContext(unitName = "persistenceUnitTest",type=PersistenceContextType.TRANSACTION)
 private EntityManager entityManager;


 @Transactional(propagation = Propagation.REQUIRED)
 public void saveRequired(Child child) {
  entityManager.persist(child);
 }
 @Transactional(propagation = Propagation.REQUIRED)
 public Child findByIdRequired(int childId) {
  return entityManager.find(Child.class, childId);
 }

 @Transactional(propagation = Propagation.REQUIRED)
 public Child saveAndFindRequired(Child child) {
  entityManager.persist(child);   
  return entityManager.find(Child.class, child.getChildId());
 }
 
}


DAOTest.java
...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "DAOTest-context.xml")
public class DAOTest {

 @Autowired
 private GenericDAO genericDAO;

 @Test
 public void testSaveDifferentPersistentContext() {
  System.out.println("------------testSaveDifferentPersistentContext(): start -------");
  Child child = new Child();
  child.setName("child");
  child.setChildId(1);
  genericDAO.saveRequired(child);
  Child findById = genericDAO.findByIdRequired(child.getChildId());
  System.out.println(findById);
  System.out.println("------------testSaveDifferentPersistentContext(): end -------");
 }
 
 @Test
 public void testSaveSamePersistentContext() {
  System.out.println("------------testSaveSamePersistentContext(): start -------");
  Child child = new Child();
  child.setName("child");
  child.setChildId(2);
  Child childFound = genericDAO.saveAndFindRequired(child);
  System.out.println(childFound);
  System.out.println("------------testSaveSamePersistentContext(): end -------");
 }
 
}




testSaveDifferentPersistentContext() is not using Persistence Context as First Level Cache


As you can see the method testSaveDifferentPersistentContext() calls saveRequired() and findByIdRequired() methods of GenericDAO. So this is what it happens:
  1. When the method saveRequired() starts, a new transaction is created;
  2. When the method persist() of the EntityManager is invoked, a new persistence context is created. Then the child entity is inserted into this persistence context;
  3. When the method saveRequired() ends, the persistence is flushed and the transaction goes to commit;
  4. the method findByIdRequired() starts and a new transaction is created;
  5. When the method find() of the EntityManager is invoked, a new persistence context is created. Then the child entity is searched in the persistence context but it's not found;
  6. the method find() retrieves the entity by performing a query on the database.

From the database point of view, let's see the query executed.

insert into Child (name, parent_parentId, childId) values ('child', '', 1)

  select
        child0_.childId as childId1_1_,
        child0_.name as name1_1_,
        child0_.parent_parentId as parent3_1_1_,
        parent1_.parentId as parentId0_0_,
        parent1_.name as name0_0_ 
    from
        Child child0_ 
    left outer join
        Parent parent1_ 
            on child0_.parent_parentId=parent1_.parentId 
    where
        child0_.childId=1



As you can see, an INSERT and a SELECT are performed. This happens because the entity searched is not present in the persistence context (that acts as a first level cache) so you need to hit the database,

testSaveSamePersistentContext() is using Persistence Context as First Level Cache


The method testSaveSamePersistentContext() calls only the method saveAndFindRequired() of GenericDAO.
  1. When the method saveAndFindRequired() starts, a new transaction is created;
  2. When the method persist() of the EntityManager is invoked, a new persistence context is created. Then the child entity is inserted into this persistence context;
  3. When the method find() of the EntityManager is invoked, a new persistence context is created. Then and the child entity is searched in the persistence context and it's found because it has just been inserted;
  4. when the method saveAndFindRequired() method ends, the persistence is flushed and the transaction goes to commit.
From the database point of view, let's see the query executed.

insert into Child (name, parent_parentId, childId) values ('child', '', 2)

As you can see only an insert is performed. This happens because the entity searched is present in the persistence context (that acts as a first level cache) so you don't need to hit the database.

Friday, July 27, 2012

Design Pattern Adapter

In the next days i'm going to talk about the most important design patterns used in java programs.
In this post i'll show the design pattern Adapter that is a structural design pattern as Bridge and Composite.

Problem


The design pattern Adapter faces the problem of transforming an "incompatible" interface of an object into another interface expected by the client.

Solution


The design pattern Adapter suggests to resolve the problem by giving to the object with the incompatible interface an interface as the client expects.

Components


  • Target: it defines an interface into the application domain and it's a possible candidate to be called by a client;
  • Adapter: it adapts the interface of Adaptee object to the Target interface;
  • Adaptee: it defines an existing interface that needs to be adapted;
  • Client: communicates with the objects that adhere with the Target interface .


Class Adapter


The Adapter class becomes a subclass of the Adaptee class and it implements the Target interface.
At this way the client can invoke a method of the Adapter class because it adheres with the Target interface and it preserves the functionalities of the existing Adaptee class.

Object Adapter


UML Rappresentation



Object Adapter


The Adapter object has a reference to the Adaptee object and it implements the Target interface.
When a client invokes a method of the Adapter interface it delegates the Adaptee a part or all of the responsibility to serve the request method.

UML Rappresentation


Consideration


Generally the design pattern Adapter is used when you're interested into exposing to a client a functionality that you know to be present in your application domain. Unfortunately the object that exposes this functionality has an incompatible interface so it cannot be called by the client.
So you have to convert the incompatible interface of your object into another interface known by the client.

Monday, July 23, 2012

Liferay Porlet Phases

In this post we'll see only a short description of the four phases of a portlet:
  • Render Phase;
  • Action Phase;
  • Resource Phase;
  • Event Phase.


Render Phase

In the Render Phase a portlet generates HTML content of its current state. This phase is invoked for all the portlet in a page when you reach that page in your navigation and after an action phase occurs on a portlet in that page. In the specification no order for the render phase of the portlets is guaranteed.

Action Phase

In the Action Phase a portlet executes functionalities that modify its state as a database update. Generally an Action Phase doesn't return nothing.
That phase can be only invoked one at a time for a portlet. This phase is planned for all the actions that cannot be repeated as a database insert, a preference modification and so on.

Resource Phase

In the Resouce Phase a portlet serves resources like PDF, DOC, etc..

Event Phase

In the Event Phase a portlet answers to events.

Conclusion

When a user interacts with a portlet performing an action, the portlet container has to delegate that action to that portlet and then it has to render the whole page. When a portlet goes to action phase, the other portlets have to go to their render phase. So you have to be carefull on the back-end functionalities involved in render and action phases

Sunday, July 22, 2012

PL/SQL Create a Package with Functions - Tutorial

In this post i'll show the syntax to write a function in PL/SQL.

CREATE TABLE

table.sql

create table employee (
   id numeric,
   name varchar2(30),
   salary numeric,
   CONSTRAINT impiegati_pk PRIMARY KEY (id)
);



CREATE PACKAGE SPECIFICATION

PackEmployee.pks
DROP PACKAGE myschema.pkg_mypackage;

CREATE OR REPLACE PACKAGE myschema.pkg_mypackage
IS

FUNCTION get_num_employee_by_name (employee_name in varchar2) RETURN number;

END pkg_mypackage;



CREATE PACKAGE BODY

PackEmployee.pkb

CREATE OR REPLACE PACKAGE BODY myschema.pkg_mypackage
IS

FUNCTION get_num_employee_by_name (employee_name in varchar2)
 RETURN number
 IS
      return_value   NUMBER := 0;
      strSQL         varchar2(3000) := '';
  
 BEGIN

     strSQL := strSQL ||'  SELECT count(imp.id)';

     strSQL := strSQL ||'  FROM employee emp ';

     strSQL := strSQL ||'  WHERE emp.name = '''|| employee_name ||'''';
      
 EXECUTE IMMEDIATE strSQL INTO return_value;

return return_value;

 END get_num_employee_by_name;


END pkg_mypackage;




INVOKE FUNCTION OF PACKAGE

invoke.sql

select myschema.pkg_mypackage.get_num_employee_by_name(‘Simone’)
from dual

PL/SQL Cursor loops


In this post i'll show a short snippet of code about loops with cursors in PL/SQL (Procedural Language/Structured Query Language) language.

A simple way to do a loop in PL/SQL language is to use cursors as shown below.

Cursor loop

for myrec in (select col1, col2 from table A)

loop
       /* here you can use myrec.col1 or myrec.col2 to access and manage fields */
end loop;


Friday, July 20, 2012

Last Executed Query in Oracle

Not so long ago I faced to the need of knowing the last SQL queries executed in oracle. Now i'm going to post the sql query that helped me solving that problem.
Oracle Query

select * from v$sql  where sql_text like 'select%' order by first_load_time desc

Tuesday, July 10, 2012

Callable and Executor (java.util.concurrent)

Callable


Callable interface has a similar behaviour of Runnable interface except for the fact that Callable has a generic method public T call(); with a return type.
You can imagine Callable interface as a task to be executed, so when you have to choose tasks and their responsibilities, you are choosing what an instance of Callable should do.

In this example we'll see a program that counts the pair numbers in a List of Integer.
To perform a quick search I have divided the list into two sublists and I assigned two tasks to search the former the head and the latter the tail of the list. Each task returns a sub-total of the count so then we have to sum these sub-totals and print the result.
It's not a good example of concurrency but it's only a way to talk about some features of java.util.concurrent package.

ExecutorService


In this example, I make use of the interface ExecutorService that provides methods to manage the start and the termination of each task.
ExecutorService permits to return for each task (Callable) a Future object that represents a pending result of a specific Callable instance.
I put each instance of Future in a list and then I ask the result to each instance of Future using get() method.

When all the instances of Future in that list return a value, I will use these values to obtain the total count.
You have to notice that ExecutorService is obtained with a static method called Executors.newFixedThreadPool(int numThread) whose numThread value represents the max number of threads to be used by the submitted tasks or Callable instances.

It's important to notice the difference between threads and tasks. The number of threads is not directly linked to the number of tasks: the number of threads is a choice that has different reasons from the number of task which is instead linked to the specific problem you are going to resolve.

MyPairCallable.java

import java.util.List;
import java.util.concurrent.Callable;

public class MyPairCallable implements Callable<Integer> {

 private int count = 0;

 private List<Integer> list;

 public MyPairCallable(List<Integer> list) {
  this.list = list;
 }

 public Integer call() throws Exception {
  for (Integer i : list) {
   if (i % 2 == 0) {
    count++;
   }
  }
  return count;
 }

}
This method returns an Integer which is subtotal of the count of the pair number in the original list.

Main.java

...

public class Main {

 public static void main(String[] args) {

  List<Integer> list = new LinkedList<Integer>();
  for (int i = 0; i < 1000; i++) {
   //int d = (int)(Math.random()*100);
   list.add(i);
  }
  System.out.println(list.size());
  List<Integer> subListFirst = list.subList(0, list.size()/2);
  List<Integer> subListSecond = list.subList(list.size()/2, list.size());
  System.out.println(subListFirst.size());
  System.out.println(subListSecond.size());
  
  ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(2);
  
  List<Future<Integer>> futures=new LinkedList<Future<Integer>>();
  futures.add(newFixedThreadPool.submit(new MyPairCallable(subListFirst)));
  futures.add(newFixedThreadPool.submit(new MyPairCallable(subListSecond)));
  int count=0;
  for(Future<Integer>future:futures){
   try {
    count=count+future.get();
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
  }
  newFixedThreadPool.shutdown();
  System.out.println(count);
 }
}

Monday, July 2, 2012

JPA EntityManager and EntityManagerFactory

One of the most important things to know about the EntityManager interface is that it's not thread safe. If a Servlet or any kind of stateless component uses the EntityManager as a shared instance, you can encounter many problems.

EntityManager


MyServlet.java

 ...

@Entity
public class MyServlet extends HttpServlet {

  @PersistenceContext(unitName="myUnit")
  private EntityManager em;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  
   ...

}
The above snippet of code is not correct.

EntityManagerFactory


MyServlet.java

 ...

@Entity
public class MyServlet extends HttpServlet {

  @PersistenceUnit(unitName="myUnit") 
  private EntityManagerFactory factory;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  EntityManager em = emf.createEntityManager()

   ...

}
The above snippet of code is correct.

Suggested Pages