February 10th, 2013  | Tags: , , ,

As you should know, Red Hat Enterprise Linux does not play some videos format, such as: divx and mkv. Although RHEL is made for companies, sometimes you must watch some videos sent by the executive team. If you’re in this situation, I advice you to install the VLC software.
VLC is a free and open source cross-platform multimedia player and framework that plays most multimedia files as well as DVD, Audio CD, VCD, and various streaming protocols.
Unfortunately it has not come by default in the RHEL’s repository, but you can easily add it through the command below:

sudo rpm -Uhv http://apt.sw.be/redhat/el6/en/x86_64/rpmforge/RPMS/rpmforge-release-0.5.2-2.el6.rf.x86_64.rpm

After that you’ll be able to install VLC through yum.

sudo yum search vlc
sudo install vlc

It’s done!! Now, you can open it and watch as much movies as you want in varies format.
This is a short post, however can be useful for anyone in the same situation. If you have any comment, fell free to leave your message below.

January 8th, 2013  | Tags: , , , , , ,

This is a short post, but can be useful for anyone who is playing either cocos2d (iOS – objective-C programming language) or cocos2d-x (multiplatform-C++ programming language) mobile game development with.
When you create a simple project into Xcode for cocos2d, you got an example like image below:
Screen Shot 2013-01-08 at 9.52.28 PM
What about changing the back to red background color? Let’s do that using objective-c first.

Object-C – Using cocos2d engine

Open the interface file and change the CCLayer to CCLayerColor:

1
@interface HelloWorldLayer : CCLayerColor <GKAchievementViewControllerDelegate, GKLeaderboardViewControllerDelegate>

Inside the class file, change the init to initWithColor method:

1
2
3
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super's" return value
	if( (self=[super initWithColor:ccc4(255, 0, 0, 255)]) ) {

You’ll got the following result:
Screen Shot 2013-01-08 at 9.57.55 PM

C++ – Using cocos2d-x engine

To get the same result as above, open up the interface file and change the CCLayer to CCLayerColor:

1
2
3
#include "cocos2d.h"
 
class HelloWorld : public cocos2d::CCLayerColor

Also, in the class file change the CCLayer to CCLayerColor and the init to initWithColor method:

1
2
3
    //////////////////////////////
    // 1. super init first
    if ( !CCLayerColor::initWithColor(ccc4(255, 0, 0, 255)) )

In cocos2d-x project, you’ll got the following screen:
Screen Shot 2013-01-08 at 10.07.04 PM

Conclusion

In both case we should use the CCLayerColor instead CCLayer. Both frameworks have the initWithColor method and we could use the ccc4 for color setting. Almost everything that you do in cocos2d, you can also do in cocos2d-x but using C++ programming language.
The source of this post is: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Chapter_2_-_How_to_Add_a_sprite
I hope everybody enjoy this post. Cya

December 12th, 2012  | Tags: , , , , , , ,

Hi there,

IBM Installation Manager tool is the required tool for installing other IBM’s products, such as: WebSphere Application Server, Rational Application Developer, Portal Server, Commerce Server and so on. If you’re not familiar with Linux and would like to get started using it, this post can be useful for you.

Before getting started, be aware that Installation Manager is a 32bits tool and because of this you may have problem installing it on a 64 bits operating system. As a workaround, I wrote the following post: http://www.jairrillo.com/blog/2012/12/12/ibm-installation-manager-libld-linux-so-2-bad-elf-interpreter-no-such-file-or-directory/.

IBM Installation Manager has the install script for installation (image below).
Console
However you must execute it with root access.

On the Linux environment, open the Console and go to the Installation Manager folder. Now, type the following to get started the installation. You’re gonna see a screen like below:

sudo ./install

obs: if requested, type the root password.
Splash Screen
After the tool is opened, you’re gonna see a screen with the IBM Installation Manager checked. Simply click on Next button.
Installation manager
The third screen talks about the license. Accept it and move on.
By default, the Installation Manager is installed in the /opt/IBM/InstallationManager folder. In the fourth screen, accept the default and click on Next.
Default options
Finally the next screen is a simple summary and then the Install button is enabled. Just click on it.
After a few minutes the IBM Installation Manager would be installed on your Linux and then you can proceed with the next IBM’s products installation.
Successful
If you are using Gnome 2, the IBM Installation Manager should appear into Applications -> System Tools menu.
Menu
As I said in the beginning, this is a dummy post, however IBM Installation Manager tool is required for other IBM’s products installation. In the next post, I’ll show you how to install WebSphere Application Server v8.5 on Linux and how to create the first Profile.
If you have any comment, fell free to leave your message below.
Thanks guys, see you soon.

December 12th, 2012  | Tags: , , ,

Recently, I’ve faced the following problem when I’ve tried to install the IBM Installation Manager on RedHat 64 bits.

bash: ./install: /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

It happened when I tried to run the ./install command inside the Installation Manager directory.
Looking at the internet, I’ve found this: . Basically, the IBM Installation Manager is a 32bits program and could not be performed on a 64bits Operating System. However there is a workaround that worked perfect for me.
As root, type the following commands:

[root@localhost]# yum install gtk2.i686
[root@localhost]# yum install libXtst.i686

After that hopefully you can run the ./install command successfully.
If you need more details, please take a look at the link above.
I hope this post be useful for anyone else. See you gu

July 6th, 2011  | Tags: , , , , ,

This is the second post about IOS that I am writing out. You can read the first one over here.
In this post I am going to talk about Object-C object oriented principles, such as: classes, interfaces, instance variables and methods. This is an important topic in object-c, therefore I advice you to read this post carefully.

Interfaces

As you should know, Object-C is Object Oriented. In any OO language, we can use interface implicitly or explicitly.
In Object-C the interface is implemented in a separated file with extension .h (header) and lives together with a class. To create an interface/class in XCode, simply right mouse click on Classes folder -> Add -> New File. On the new window, select Object-C class and subclass NSObject:
.
XCode is going to create two files, an interface (.h) and the class (.m).
Let’s see an interface example:

1
2
3
4
5
6
7
8
9
10
#import <Foundation/Foundation.h>
 
@interface Shape : NSObject {
@private
	NSString *color;
	CGPoint *position;
}
-(void)setColor:(NSString *)aColor;
-(void)drawShape;
@end

Let’s study the code above.
First of all, the interface has the directive @interface and ONLY on it we can create inheritance. In the example above, our interface Shape inherits from NSObject.
Note: 1 – Other languages, such as Java and C#, the inheritance occurs in the class. In Object C, only the interface has inheritance. 2 – NSObject is the most common object from Cocoa Touch Framework.
In the interface, we have the #import statement. In our example, we imported the Foundation.h interface that belongs to Cocoa framework.
Another weird behavior: Instance variables can be only defined in the interface and inside the { } signs. In our example, there are two instance variables (color and position). Also, both instance variables have the private visibility, in other words, nobody can access these variables outside of this interface/class.
Finally, the method signature is defined outside the { } signs. Our example has two methods.

Class

A class, also known as implementation in object-c, has the extension .m. It implements all methods from its interface. See the example below:

1
2
3
4
5
6
7
8
9
#import "Shape.h"
@implementation Shape
-(void)setColor:(NSString *)aColor {
	color = aColor;
}
-(void)drawShape {
	NSLog(@"Drawing a shape...");
}
@end

The implementation has the @implementation directive and imports the interface through #import “Shape.h” line. Different from other languages, if you do not implement ALL methods on the class, there will not be a compiler error.
As you can see, the class does not have the { } signs and instance variables definitions. Also, there is no inheritance. All of this behaviors are implemented in the interface.

Instance Variables

As already said, instance variables are defined in the interface and within the { } signs. Another important point here is the pointer sign (*). ALL instance variables must be defined as a pointer. Also, all instance variables go to memory HEAP when created (we’ll see how it works in this post yet).
Within the { } signs we also define the visibility. By default, the visibility is protected, but in OO, usually we define the instance variables as private and we use some methods to access those variables. If you have no idea what private, protected or public are, please, google about Object Oriented Visibility.

Methods

Certainly it is the weirdest thing in this topic. We’ve already showed two methods examples:

1
2
-(void)setColor:(NSString *)aColor;
-(void)drawShape;

The first one receives a parameter and the second has no parameter. To define a parameter for a method, we use the following syntax: method name : (parameter type) parameter name; Weird? not so far, but what about multiples parameters? Let’s see another example from a war game:

1
-(NSArray *)shipsAtPoint:(CGPoint *)bombLocation withDamage:(BOOL)damaged;

What’s the method name? How many parameters do we have? Looks like method’s name and parameters are messed up, right?. Yes, that’s right, you put the parameters inside the method name and read it directly. Thus the method’s name above is shipsAtPointWithDamage and it has two parameters.
The most languages has the full method name and then the parameters split by comma, like example below in Java:

1
public AnyObject[] shipsAtPointWithDamage(CGPoint point, Boolean damaged);

What about four parameters?

1
2
3
4
-(void)splitViewController:(UISplitViewController *) svc 
	willHideViewController:(UIViewController *) aViewController 
	withBarButtonItem:(UIBarButtonItem *) barButtonItem 
	forPopoverController:(UIPopoverController *) popoverController;

Man, that’s really weird. Honestly, I did not get used with this syntax yet.
Finally, let’s talk about the minus sign.
Minus sign means that the methods are instance methods, in other words, it can access the instance variables. Plus means that the methods are class methods. It cannot access instance variables. Usually used for global methods. You do not need a class instance to access it (Similar, but not identical, to static in Java).

Instantiating a Class

Probably you already heard this phrase: Object is a class instantiated. But how can we instantiate a class in object-c?
Usually we use a couple of methods: alloc and init. See example below:

1
shape = [[Shape alloc] init];

Do not worry about [ ] yet. Just see the alloc and init methods. To create an object, we must alloc it in the HEAP memory. It is done through the alloc message. Also, we need to initiate it. It is done through a method that starts with the first four letters “init”. It’s common see an init method called: initWithAnyValue…
Init works like constructor of languages such as Java and C#.

Sending message to a method

Unlike Java or plain C, Objective-C works with messages. You don’t invoke a method on an object, instead, you send a message to it (like the Ruby language). Supposing our example SHAPE, we have the object shape (it’s the receiver) and we want to send a message to it to draw something (remember, we’ve got a draw method).

[shape drawShape];

You send messages inside the brackets [ ].
What about the code below?

[shape transform]

We do not have the method transform, so we’ll get a compiler error, right? No, because we are not invoking a method to an object, we are sending a message to an object (or receiver). In this case, the message is “transform”, but we do not have the transform method, thus, the compiler will show up a warning, but not an error. (carefully with this behavior).

Hands on

Let’s create a simple example to practice the class creation, inheritance, instance variables and method. Actually, I’m not going to show up step-by-step, instead, I’m going to tell you what the exercise is and you’ll do it yourself alone (hopefully). In the end of this topic, there’s a link to download the exercise done. (Promise that you’ll download the exercise just for conference).
The exercise looks simple. First: create more two classes (Circle and Rectangle) that inherits from Shape. Both classes must implement the drawShape method and print out the string “Circle or Rectangle”, also, first print out the content of the drawShape from superclass. To print out a content, use the NSLog method like the drawShape example.
Note: To call a method in the superclass, send a message to it using [super drawShape];
Create an User Interface that has two buttons (Circle and Rectangle). Each on acts a different method on the Controller. The controller instantiates the Circle or Rectangle class and call the drawShape method.
To see the output of NSLog inside the Xcode, go to menu Run -> Console. A new window will be opened. Now, let’s get started.

Conclusion

Although there are many things to say about class, interface, instance variables and methods, I guess this topic is a good starting point. I advice you, look at Mac Developers site about these topics and read the official documentation carefully. Also, there’re many blogs on the web that talks about object-c.

The next topic we’re going to talk a little more about instance variables and methods. Actually, we’re going to talk about the @property and @synthesize directives. Also, we’re going to talk about another important concept: Dot Operation.

If you have any question, fell free to leave your comment below.

Download the exercise here.

June 27th, 2011  | Tags:

If you’re familiar with Android, probably you have already created a button on the user interface and implemented a controller method to respond to this button’s action. This can be done through the OnClickListener interface and its onClick(View) method. A example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class TesteApp extends Activity implements OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View view = findViewById(R.id.button1);
        view.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
    	//Implements the action over here.
    }
}

On line 1, we used OnClickListener interface. This interface provides us the onClick(View) method. Also, on line 6 and 7, we set up the Listener to the Button widget.
Since Android version 1.6 (API level 4), Android offers us an android:onClick UI Method. Using this approach, you do not need to implement the OnClickListener interface and also you do not need to implement the static onClick(View) method. Rather than, you can bind the android:onClick method directly to a method on the Activity. See the example below:
User Interface – main.xml

	<Button android:text="Click me" android:id="@+id/button1"
		android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="buttonPressed"></Button>

In the UI above, we set up the onClick to a method called buttonPressed.
Java class – Activity

1
2
3
4
5
6
7
8
9
10
public class TesteApp extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void buttonPressed(View v) {
    	//Implements the action over here.
    }
}

As you can see, the Activity above does not implement the OnClickListener. Also, the widget does not need to set up its Listener pragmatically. This way you write less code and your class get cleaner.

As far as I know, both ways work similar. There’s no performance issue or anything else. However the OnClickListener interface provides more methods than onClick. So, if you only need the onClick function, I advice you to use the android:onClick. If you need anything else, I advice you to implement the OnClickListener interface.

If you have any question, fell free to leave your comment below.

June 18th, 2011  | Tags: , , , , ,

If you want to build Iphone,IPad or IPod touch applications, this can be a start pointing for you.
I’m gonna write a series of posts about IOS as long as I am studying this platform. For a complete material, take a look at the apple’s developer area.
In this first post, I’m gonna show you how to get started with IOS, such as: showing the pre-requirements, downloading the tools and finally a simple example binding the User Interface (UI) and the controller (Object-c classes).

Pre Requirement

First of all, if you wanna build applications using IOS, you MUST have a MAC computer.
For coding and designing, we’re gonna use the following tools: Xcode for coding and Interface Builder for designing. Basically you can choices either Xcode 3.2.6 for free or Xcode 4.0 Free for Mac Developer or purchase it from AppStore. In both, one single download will get Xcode and Interface Builder (Xcode 4 brings Interface Builder integrated within Xcode). In this topic, I’m gonna use version 3.2.6.
Real Iphone, Ipad or IPod touch is not required, because Xcode has an emulator inside it. Furthermore, if you want to deploy your application on a real device, you must become a Mac Developer, otherwise you will test your application only on the emulator.

Concepts

IOS uses object-c as programming language. It is an OO language, but its structure looks weird for whom comes from another OO language such Java. Also, Object-C has some features similar to C and C++, such as: pointer, memory management and so on.
By default, IOS uses the Cocoa Touch Framework. It’s obvious that all my posts are gonna talk just about this framework.
IOS programming is based on MVC pattern (model – view – controller). If you have no idea what it is, please, google it.

Creating a new project

Click on Xcode icon to launch Xcode. Yo’re gonna see a splash screen like below:

Choose the “Create a new Xcode Project”. On the next screen, choose “View Based Application” and click on Choose button. For this example, I have chosen the name “Class1″ as project name.
After these steps, the Xcode will be opened and some default files created. Image below show up the Xcode interface and the project files.

For this post, we’re gonna work on in the following files: Class1ViewController.h, Class1ViewController.m and Class1ViewController.xib. Class1 is the name of my project, because of this Xcode has created the classes using this Class1* nomenclature.

Editing the interface and implementations

When you start a new application, you can start by different parts of the software. Someone prefer starting by the model, other by designing and so on. Usually I like starting by model, but for this example I’ll start by designing the UI. Thus, the first task to do is to create the objects within the Controller that will represent the UI widgets.
Our first application is gonna be really simple. There will be one TextField where the user can put his name, a button to submit an action and a label that will print the name of the user. So, let’s get started it.

Open up the Class1ViewController.h file. It is the interface file. Write the following lines of code.

#import 
 
@interface Class1ViewController : UIViewController {
	IBOutlet UITextField *fieldName;
	IBOutlet UILabel *displayName;
}
-(IBAction) submitPressed;
@end

Different from other languages, such as Java, the interface is the unique local where you can define your instance variables (inside the { }). Everything out from { } are method signature. We’re gonna talk about interface, classes, methods and attribute in another post.
In the code above, the important is to see that we have two instance variables that represent a TextField and Label from User Interface. Furthermore, there is a method called submitPressed. Note: both attributes uses pointer as well as all objects in Object-C must use too.
What about IBOutlet and IBAction? Both are empty object that Interface Build can recognize them. Without this objects, would be impossible to binding the UI widget with our controller.

Building Interface

Before implement the controller (we just coded the controller’s interface), let’s draw our interface using Interface Builder. To do that, double click on Class1Controller.xib file. Interface Builder will be launched.

As you can see, some windows are opened. The Library window contains the UI widgets. The View window is the place where you are gonna draw the interface. Class1ViewController.xib window is where the bind occurs, as well as the View Attributes window is where you can change the UI widget behavior.
Let’s create a screen using only the UITextField, UILabel and UIButton. Look at the image below:

As I said, really simple.

Binding the UI widgets and the Controller’s object

This section is the main goal of the post. If you are familiar with Android, you’re gonna see that IOS is simpler than Android for binding.
First, on Class1ViewController.xib window, click and hold the “File’s Owner” icon, hold Control button and go to the UITextField widget. A blue arrow will appear. When you release the mouse and control button, a pop-up will appear with the available options for binding. Choose the attribute “fieldName”.
Repeat the process for the UILabel “Your name is” and binding it to the attribute “displayName”.

We do not have a attribute for the Submit button, however we have a method signature. Thus, we binding a button with its action, in this case, a method.
Simply repeat the process, however clicking first in the button Submit and then go to the File’s owner.

After that, the binding between the UI and the Controller is done.

Implementing the Controller

Now it is time to implement our controller. Open up the Class1ViewController.h file and implement the method “submitPressed” like code below:

#import "Class1ViewController.h"
 
@implementation Class1ViewController
-(IBAction) submitPressed
{
	//Get the text from UIText
	NSString *yourName = [fieldName text];
	//Prepare a static phrase
	NSString *staticPhrase = @"Your name is: ";
	//Put the staticPrase + yourName in the UILabel content
	[displayName setText:[staticPhrase stringByAppendingString:yourName]];
}
@end

It is not the goal of this topic explain how object-c works, however let’s take a look at the code above.
First, only the method implementation is inside the class. As I said earlier, the attributes/instance variables stay in the interface.
NSString is the String type used in the Cocoa Touch Framework. Also, as I said, all objects use pointer.
The messages are send out through brackets ([ ]) in a object. It looks weird, but I promise, you will get used to it.
Finally, the NSString API has a lot of useful methods. Different from other languages that uses the plus sign to concatenate two strings, NSString has a method called “stringByAppendingString”. If you want to create real applications for IPhone, Ipad or Ipod touch, you MUST take a deep look at the NSString API.

Running the application

Make sure you’re using the proper emulator. For this example, we’re using IPhone. Look at the right up corner of XCode.

After that, click on “Build and Run” button and the emulator will launch. It looks a Iphone device with its features. Now, you can test your first application.

Conclusion

The major goal of this topic is to present you how to get started in IOS development. After read this topic, you will be able to create a new IPhone,Ipad,Ipod Touch application, create a simple UI and binding the widgets to the controller.
In the next post, I’ll talk more about object-c, such as: interface, class, method, attributes, messages and so on.

If you have any question, fell free to leave your comment below. I hope this topic be useful for anyone.

November 16th, 2010  | Tags: , ,

This is a short and useful link for whom wants to resize multiples images on Ubuntu. First of all, back up your images file before read/run the tips from this tutorial.

The simplest way to resize multiples files is through command line using a tool called mogrify. On Ubuntu 10.04 this tool is installed by default, however if you’re using an older version, you can install it through the command

sudo apt-get install imagemagick

After that, the command to resize multiples files is really simple:

mogrify -resize 1024 *.jpg

Of course you can use more parameters, however the command above will resize all pictures to 1024 pixels.

If you have any comment or question about this topic, fell free to leave your comment below. I hope this topic be useful for anyone else.

September 26th, 2010  | Tags: , , , ,

After a long time, I have decided to write a simple but useful post for whom is working in a WEB 2 application using PHP as script language.
Certainly you have already heard about JQuery. In this topic we’re going to show up how to use AJAX with PHP. Furthermore, we’re going to show up an example using JQuery + AJAX + PHP + JSON.

First Example – JQuery + AJAX + PHP

In the first example, we’re going to create a simple page (index.php) with a single text field and a button. When the user clicks on the button, an ajax call will be fired.
The content of the text field will be sent out to a PHP file (ajaxExample.php) and it will return the content in uppercase. Finally, the new content will be displayed in the first page (index.php).
All of those actions are going to be performed in an AJAX way. Hands on.

index.php

As said, there will be a text field and a button in the index.php. Check it out the code below:

<html>
<head>
	<script type='text/javascript' src='js/jquery.js'></script>
</head>
<body>
	<h2>JQuery + AJAX + PHP - First Example</h2>
	<form>
		Name: <input type="text" name="name" id="name" /><br />
		<input type="button" id="button" value="Click me" />	
	</form>
        <div id="loading">Loading...</div>
	<div id="result" />
</body>
</html>

Nothing special on the code above. On line 3 we have added the JQuery file. Also, we have the form with the text field and the button and two DIVs: one to show the loading string and the other one to show the result. Now, go to the next step.

ajaxExample.php

This is the simplest file. Basically it gets the value from the name attribute, wait for 2 seconds and return the name in uppercase mode.

<?php
$name = $_POST['name'];
sleep(2);
echo strtoupper($name);
?>

JQuery and AJAX Code

Finally, let’s the see cool part, where the JQuery call the ajax function. Let’s see the code:

	$(function() {
		$("#loading").hide();
		$("#button").click(function() {
			$.ajax({
				type: 'POST',
				data: 'name=' + $("#name").val() ,
				url: 'ajaxExample.php',
				success: function(data) {
					$("#loading").hide();
					$("#result").text(data);
				},
				beforeSend: function() {
					$("#loading").show();
				}
			});		
		});
	});

The code above makes the ajax call. As you can see, the code is straightforward, but If you need more information about the parameters, please check the JQuery AJAX API.
Now, run the application and you’re gonna see how the code works.

If you prefer, you can download the example above here.

JSON

If you’re not familiar with JSON, please check this site out.
JQuery handles JSON usando the JSON.parse method. In the PHP side, there are two methods: encode_json and decode_json. Let’s see another example:

index.php

<html>
<head>
	<script type="text/javascript" src="js/jquery.js"></script>
	<script type="text/javascript">
		$(function() {
			$("#result").hide();
			$("#json_anchor").click(function() {				
				json_call();
			});
		});	
 
		function json_call() {
			$.ajax({
				type: 'POST',
				url: 'json.php',
				success: function(data) {										
					var myObject = JSON.parse(data);
					$("#name").text(myObject.name);
					$("#age").text(myObject.age);			
					$("#result").show();		
				}
			});
		}
	</script>
</head>
<body>
	<h2>Hello JSON + PHP World</h2>
	<a href="#" id="json_anchor">Click here</a>
	<div id="result">
		<table border="0">
			<tr>
				<td width="50px"><strong>Name</strong></td>
				<td id="name"></td>		
			</tr>
			<tr>
				<td><strong>Age</strong></td>
				<td id="age"></td>		
			</tr>
		</table>
	</div>
</body>
</html>

json.php

<?php
	require_once('Customer.class.php');
	$customer = new Customer('Jair',28);
	echo json_encode($customer);
?>

See above, we’re using the json_encode method to transform an object (Customer) into a JSON object.

Customer.class.php

<?php
class Customer {
 
	public $name;
	public $age;
 
	function __construct($name, $age) {
		$this->name = $name;
		$this->age	= $age;
	}
}
?>

Running the example you’re gonna see a link. When the user clicks on the Link a table with the name and age will be displayed. This call is made by AJAX.
You can download this example here.

As you can see, use JQuery is useful for AJAX call. The biggest advance of JQuery, is that you can use JQuery with almost any language: PHP, Ruby, Java and so on. I hope this topic be useful for anyone.
If you have any question or comment, fell free to let your message below

March 13th, 2010  | Tags: , , , , , ,

This is the third part of a series of posts about JPA 2 and Netbeans 6. This series has the goal to show up how to get started with JPA 2, as well as creating complex model using relationship and inheritance.
Part three is gonna use the same example than Part 1, but now we’re going to use the query mechanism to retrieve values from database.

Requirement

  • Understand JPA concepts – If you have no idea what JPA is, please google it first
  • Netbeans 6.8 and glassfish v3 installed
  • MySQL database installed – If you have another one, make sure you have the JDBC driver
  • Read Part 1 and have the database and POJO already created.

Querying strategy

The most common way to retrieve values from relational databases is through an SQL Select Query, probably you have already wrote a lot of them. JPA has this ability and much more.
Since version one, JPA allows you to retrieve values from native query, JPA-QL and NamedQuery, which uses JPA-QL. In version 2, JPA brings us another great API, Criteria API.

Native Query

Let’s get started with the most popular, but less used in JPA: Native Query.
This kind of query must be used only when you need a specific command/resource from the database. Creating many specific queries, your application is going to be dependent from the database, it can be a disadvantage.
To use the native query, simply use the createNativeQuery method from EntityManager. Let’s see the same example from part 1, but using the Native Query.

    public static void main(String[] args) {
        EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("JPAExample01PU");
        EntityManager em = emFactory.createEntityManager();
        List<Products> listProducts = em.createNativeQuery("select * from products", Products.class).getResultList();
        for (Products product : listProducts) {
            System.out.println("Product: " + product.getDescription());
            System.out.println("Price: " + product.getPrice());
            System.out.println("---------------------------------------");
        }
    }

The change happened on line 4. We have added the createNativeQuery method. The first parameter is the Select Query itself and the second one is the class where the result must be mapped.

JPA-QL

This is the query language for JPA. It is similar than SQL, but it uses object approach. There is a method called createQuery that returns a list of objects. See the example

List<Products> listProducts = em.createQuery("select p from Products p").getResultList();

The example above seems similar than the NativeQuery, but the biggest difference appear when you use JOIN. Supposing our Products table has a relationship with another table called Categories. We could create a JPA Query like this:

List<Products> listProducts = em.createQuery("select p from Products p inner join p.categories").getResultList();

We’re going to talk about relationship in Part 5.

NamedQuery

NamedQuery is the kind of querying that we used in part 1 of this guide. The NamedQuery is written using JPA-HQ and we use the createNamedQuery method to call it. The NamedQuery lives in the Entity class and has the annotation @NamedQuery.
If you understand JPA-QL, certainly you’ll not find any problem to use NamedQuery.

Criteria

Criteria API is the newest API in JPA 2. If you’re familiar with Hibernate, like me, certainly you liked this API in JPA 2.
As Criteria API is new, it deserves an unique post for it. Part 4 of this guide is exclusive for Criteria.

Best Practices

One of the most common question regarding querying in JPA is where to use them. The simple answer could be:

  • Native Qurery: When you need a specific command/resource from the database that a JPA-QL doesn’t offer
  • JPA-QL: When you have a static query
  • NamedQuery: When you have a static query that doesn’t change, use it instead Criteria
  • Criteria: When you have a dynamic query

This post ends here, but in the Part 4 we’re going to keep talking about querying, but we’re only talk about Criteria API.
If you have any question or comment, fell free to leave your message below. I hope this topic be useful for anyone else.

TOP