Monday, June 27, 2011

How to Connect JDBC Driver to a Java Program

Well, when you do programming, its quite common to work with databases. So many people use mysql as their database in most of the cases. So I thought it will be useful for the newcomers to learn how to connect mysql to a java program.

Assuming you have installed mysql in your machine lets look at how we write our codes.
or here are the links for you to get them. :)
Get JDBC Driver for Ubuntu
MySQL-Query-Browser

First you need to create a database for your purpose.

Here is the code for creating a database using mysql -

In Query Browser
CREATE DATABASE testdb;

in phpmyadmin
CREATE DATABASE testdb;
USE testdb;

Then you need to define the tables. Lets create a table called Student including student id, name, address as the fields.

create table student(
stu_id int (2),
stu_name varchar (20),
stu_address varchar (50)
);

Now you need to open your IDE, in my case its Netbeans.

Now create a New Java project giving a name - i.e. testdb
Now goto Libraries in the left panel & right click to get the menu & select add a librabry
From the menu select  
MYSQL JDBC Driver - mysql-connector-java-5.1.6-bin.jar
(you need to download this first from the site)

Then in the java file you need to import below package.
import java.sql.*;

Now within the main method, write these codes

      Connection con = null;
       String url = "jdbc:mysql://localhost:3306/testdb";
       String user = "root";
       String password = "root";


Here you should give your database username & password.
Then within a try block you need to write this.
          con = DriverManager.getConnection(url, user, password);
           Statement st = con.createStatement();


Now you are ready to write queries to insert/upadate & delete records in the table.

1. Insert data to the Database table.

         String sql = ("INSERT student VALUES   ('1','Saman','Colombo')");                                   
      st.executeUpdate(sql);
          System.out.println("Entered");

2. Selecting & Displaying Results

 ResultSet rs = st.executeQuery("SELECT * FROM student WHERE user_id ='1'");       

   while(rs.next())  {      
           int id = rs.getInt("userstu_id");          
          String name = rs.getString("stu_name");       
          String address = rs.getString("stu_address");     
          System.out.println("ID :" + id);        
         System.out.println("Name :" + name);   
         System.out.println("Address :" + address);         
}

3. Deleting Data from the Table

String sql1 = ("DELETE FROM user_info");
st.executeUpdate(sql1);

So hope this little push would help you out guyz. Try more things your own :)


Sunday, June 26, 2011

What is pom.xml

POM is a xml file which contains the project configuration details used by Maven. It provides all the configuration required for a project. POM means Project Object Model & as the name suggests it defines the model of the project as well. In the normal project development you will add jar files & libraries  as required. In maven based development, those jars, libraries are added to the project using this pom.xml. In the pom context we call those jars, libraries as Dependencies.
A sample pom.xml would be like this.


Useful Maven Commands

1. Compiling Maven Project

To compile a maven project open terminal & go to project folder & type
 mvn compile
or
mvn clean compile

Both commands will compile the maven project but mvn clean compile will always compile the project as newer project so that older compiled versions will be cleaned. So it is good to use clean compile to have a CLEAN project ;)

2. Installing or building the project

Type the following
mvn install
or
mvn clean install

This will compile, test & package the project into war or jar.

3. Offline usage
To work offline use commands as follows

mvn -o compile
mvn -o install
mvn -o test








Creating a Maven based project


Open the terminal & go to the folder where you need to create the project.
Type the following command.

mvn archetype:create -DgroupId=com.maven.test -DartifactId=TestProject -DarchetypeArtifactId=maven-archetype-webapp

Here DgroupId means the group ID of the project & artifact Id is the project name. you can define both these & remember to give groupId seperated by the dot(.). so the output would be like this.

This will create a nice looking folder structure :)
Within your project folder you can see a POM file & src folder. before opening this using netbeans you need to add another folder named "java" inside main folder.so your main folder would look like this.
Now you can add the java, jsp, servelts, as required & also you can use any ORM like openJPA or Hibernate.


Now open the pom.xml file in the project folder. I will tell about pom.xml more in my next post. Till then this quick guide will help you out to develop a maven project :)
Initially your pom.xml would look like below.
Here you need to define the dependencies as per your requirements. for example of you are using Spring & Hibernate you need to add all the dependencies here. These dependencies will be the jar files & the libraries in the project.

After that you can open the maven based project using Netbeans.
1. Go to Netbeans & go to Open Project menu
2. browse for the location of the project & you will see ma symbols in front of the project name.
3. open the project

Then your project folder in the Netbeans would be look like this.

Then you need to build a war file in order to run the project. I am using tomcat as my server.
Now type the below to clean & build a war file
mvn clean install

Then goto your project folder & you will see a new folder called target is created & open the folder & you can see a .war file is created. (TestProject.war)
Copy this .war & goto web apps folder  in tomcat & paste it.
You can do this using tomcat manager as well. There you will find at the bottom  a place to browse for .war file & upload. you can do it either ways :)

now you need to compile the project using mvn compile & type the url of the home page of your project to run the project.
Now you will see the output like this :)
So thats it. Follow the steps & enjoy maven developments :)

A Quick Guide to Maven 3.0

In a previous post, I told you guys how to set up maven in your machine. Now let me give you a brief introduction about apache maven & how to use it in your developments.
Apache Maven is a software project management tool where programmers can easily manage the development process. Maven allows us to maintain & stick into a certain building structure & work according to a guided pattern.Maven gives a standard way of building java projects & we can use ORM (Object Relational Mapping) methods together with the Maven.
Basically Maven will create a project folder structure which is very clean & clear. standard programmers always looking for structured development techniques & thus Maven is the best solution for them.



Saturday, June 11, 2011

What is JPA

JPA means Java Persistence API & it is a framework used to manage the relational data in applications. JPA will allow programmers to change the traditional database approach by giving a newer way of accessing the database entities. 
in the normal database context, you will have a database created using mysql, sql or oracle & you gonna need to write queries to access the database entities & do whatever the transactions. but when the database is too large & the queries getting complex, the access will be time consuming & complex as well. So that developers needed a light weight method to access database objects in a faster way. Thats where the concept of JPA come in to play. 
Before JPA there were several persistence units such as  JDBC, ODB, JDO, etc. JPA combines all the best features of all & present in a sophisticated manner. Following are the comparison of JPA with others.

In JPA, the database objects are created & programmer access these objects not the database entities itself. As java is Object Oriented, this method is quite faster than traditional relational database approach. JPA will map the database entities to database objects so that you can access the data via the objects. There are many ORM methods such as openJPA, Hibernate, etc. 
To use JPA you need to import the package javax.persistence to your working environment. 





How To Install Eclipse IDE in Ubuntu

Right. last time you installed Netbeans IDE & this time I'm gonna tell you how to install Eclipse in Ubuntu.
Step 1
Download the latest Eclipse IDE from here - Eclipse Home Page
Here you can select the suitable IDE that you are looking for, for example java-developers , eclipse-ide-java-ee-developers,  etc.
There are multiple versions as well such as Helios, Galileo, Classic, etc. I use Helios SR2 version.
Step 2
After the download completed, you will have a tar.gz file like this - eclipse-jee-helios-SR2-linux-gtk.tar.gz
Now select the partitions where you want Eclipse to be installed & copy the .gz file there.

Step 3
Now right click on the .gz file & select Extract here. 
This will create a folder containing the Eclipse IDE & its components.

Step 4
In Eclipse you don't need any special installations series like in Netbeans, extracting will do the installation itself.
Now all you need to do is to open the extracted folder & double click on the eclipse.exe.
you will see eclipse is loading.

Step5
You will be Prompted to select the workspace for Eclipse to work with. 
There you need to select a place in your home folder. 
By default the path will be like yourhomefoldername/workspace, but you can always change this to your own.

Now you have configured Eclipse IDE successfully. Feel free to enjoy the IDE & show your colors :)





Saturday, June 4, 2011

How to Install Netbeans IDE in Ubuntu

Lets see how to install Netbeans IDE in Ubuntu step by step.

Step1
First you need to download the IDE from Netbeans Download page

Step 2
Select platform as Linux(x86/x64) from the upper right corner tab.

Step 3
Select the type of version you need. For example you can select java, javaFX, complete, etc .

Step 4
Then you are clear to press Download button. It will start downloading a xx.sh file

Step 5
When the downloading finished, copy the downloaded file to the directory where you wish to install Netbeans.

Step 6
Then open the terminal & enter this command to run the installation by Ubuntu.
sh netbeans-6.9.1-ml-linux.sh
 (note that here you should copy the name of your downloaded netbeans IDE)

Step 7
After some initial steps Ubuntu will give the control to the IDE itself to continue the installation.
Please follow the on-screen instructions carefully by clicking Next button respectively.

Step 8
It will take some time to install the IDE & when its done, you can open the IDE & thats it.
Now you are going to be a java expert ;)



How to Install Maven in Ubuntu

Step 1
First you need to download Maven from the maven site : http://maven.apache.org/download.html
Select the latest version of Maven & make sure to download the *.tar.gz version.
eg : apache-maven-3.0.3-bin.tar.gz

Step 2
Now you have the gz file with you & copy the gz file to the place where you want it to be installed.

Step 3
right click on the .gz file & select Extract Here option.

Step 4
Now copy the path of the Maven folder.
You can do this by right clicking the folder tab & select copy; it will copy the path.

Step 4
Now go to your Home Folder

Step 5
go to View menu & click on Show hidden Files menu. View -> Show hidden Files
or press ctrl+H

Step 6
Now start typing .bashrc in the Home Folder & then .bashrc file will be selected.

Step 7
Double click to open it & goto the bottom of the page.

Step 8
Insert these two commands to set the path for the Maven.

EXPORT MAVEN HOME =/home/yourname/foldername/apache-maven-3.0.3
EXPORT PATH = $MAVEN_HOME/bin:$PATH

Step 9
Right now you are done with maven. check whether it is working correctly by inserting this command in the terminal.
mvn -v

This will display a set of statements as below.

Apache Maven 3.0.3 (r1075438; 2011-02-28 23:01:09+0530)
Maven home: /home/xxxxxxxxx/myprograms/apache-maven-3.0.3
Java version: 1.6.0_25, vendor: Sun Microsystems Inc.
Java home: /usr/lib/jvm/java-6-sun-1.6.0.25/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.38-8-generic", arch: "amd64", family: "unix"

If you can see something similar to above, be happy. because oyu have successfully installed maven in your machine. :)

how to Install java in Ubuntu

Step 1
Make sure you are connected to Internet.

Step 2
Open the terminal (normally it is in the upper panel right after the firefox).

Step 3
type this command or copy & paste.
sudo apt-get install sun-java6-jdk

Step 4
Enter your account password in front of "[sudo] password for yourname"

Step 5
Then the rest is up to Internet & it will download the java from the source.

When you install this way, you don't need to set the path in .bashrc file for java. So that's how you install java. Now you are ready to explore the java world :)

Welcome Friends !!!

Well, this is for the people who come up with some problems when working with java & java related technologies. You will be exposed to java, hibernate, openJPA, jsp, servlets , databases, & many more from this "JavaHowTo". So, stay up-to-date to get solutions for your mind blowing problems.
Cheers,