Pages

Tuesday, 28 May 2013

Hibernate Setup and Basics

Hibernate :

1)is an ORM tool

2)used in the data layer of the application

3)provides lot of advantages over JDBC.

First Understand this problem.



Employee Class
EmpId   long
Name String
Designation String
Location String
     








Object



Relation

EmpId  bigint
Name varchar
Designation  varchar
Location varchar
























We have an Employee Class and Employee Table.

but how can we save employee object inside employee table.

yes we can do it by using traditional JDBC using Insert query.

Disadvantages if we use JDBC.

we need to design the Database, if we use hibernate it will take care of it.

we need to write sql queries to each DB operation, using Hibernate API, no need to write these queries just call hibernate APIs.

many other advantages of hibernate which jdbc alone can not give it like caching and etc.

lets see Hibernate Setup

1)download hibernate from the website hibernate Download

refer the below screenshot for the same.






2)Unzip the downloaded zipped folder.

3)Create a new java project in eclipse and set the build path with the following jars from the downloaded unzipped bundle



4)Install the Database and add its driver jar to project classpath, i have added mysql jar as i have installed mysql db.



5)Now create the most important config file for hibernate - hibernate.cfg.xml

code is as below and change the username passwd database details based on your settings.


<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>

<property name="hibernate.search.default.directory_provider">filesystem</property>
<property name="hibernate.search.default.indexBase">target/indexes</property>

<!-- maps the associated model classes -->
<mapping class="com.kb.model.Employee"/>

</session-factory>
</hibernate-configuration>


6)Create a model class and add it to hibernate.cfg.xml as shown above in bold.

code is as below

package com.kb.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {
@Id
private long empId;
private String firstName;
private String lastName;
private String role;
public long getEmpId() {
return empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}

}
observe the 2 minimum reqd annotations @entity and @id

@entity - says hibernate that this entity has to be persisted in the DB.

@id - says that this attribute must be the primary key in the table.

Now create a client program which uses hibernate api to persist the Employee object.

package com.kb.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.kb.model.Employee;

public class Client1 {

@SuppressWarnings("deprecation")
public static void main(String[] args) {
Employee emp = new Employee();
emp.setEmpId(10655697);
emp.setFirstName("lingu");
emp.setLastName("gc");
emp.setRole("SE");

// Hibernate API to persist employee object

SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
session.save(emp);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
} finally {
session.close();
}

}

}

here we have used hibernate session's save method to persist employee emp object.
this save method internally generates sql insert query according to mysql syntax and runs it using JDBC.
but as a programmer we dont have to care about it.

Now run the above client program and see the following output in mysql query broswer



Lets see further hibernate concepts in the next post.

Friday, 24 May 2013

Maven usage

Maven to software  development

First go to start->run->cmd prompt

go to the path where you want the maven project to be placed.

Run the mvn archetype:generate command as shown below.



Now select the number which indicates the type of the project,
in below image, i have selected 6 for simple core java project and also enter group id,artifact id,version and package


now check the workspace selected , maven produced a nice project structure


Now develop all source code in that workspace.
lets assume we have done coding, so we need to compile and build our application
so issue mvn clean install command as below




Now check the project folder, there will be a target folder which is having all .class files compiled using maven command.
and also there will be a jar file for the application as its a core java application.

Wednesday, 22 May 2013

Maven Setup Basics



Maven - Setup by downloading latest release.

Maven uses in software development
Lets see the maven setup step by step

1)Download the latest maven from the link  Maven download link
currently refer the latest version marked in the below image





2)unzip the downloaded maven zipped folder to any of your favorite location


3)set the following  Environment variables

1)JAVA_HOME - point to jdk folder of your java installed location
2)M2_HOME - point to  maven folder of your maven extracted location
3)PATH - bin of above 2 variables

Screenshots for the same are as below





4)Now check the maven is configured or not by issuing following command from comman prompt
mvn -version



Maven setup in your system is completed now.

Next post -  we will see how can we use maven to simplify our software development.

Friday, 26 April 2013

Spring AOP

Spring Aspect Oriented Programming is powerful feature of spring

Each application will have some global function/feature to do which applies for all/many/some of the objects depending on the requirement.

To achive such global function/feature spring AOP provides very powerful and effective way.

Basic Terms in AOP

1)Aspect - cross cutting concern ,something global feature of the application.

2)Join Point - point during the execution of the program such as method execution or exception handling code. in simple words the point where the cross cutting concerns can be applied

3)Advice - the Action taken at the join point. means implementation of any global feature/cross cutting feature.

4)Point cut - Expression which matches the exact join points.


Example program

below is the registration program which has the logic for registration.






below is the login program which has the login logic.

 

Now assume i want to have audit details where i want to store each action like register/login etc in some table.
Means basically , iwant to fire insert query to DB on execution of each of the above program.

so what could be done

without AOP, we can call insert query in each of the programs above.
but what if there are 100 such different actions/programs in our applications ?
we need to write insert query in 100 places  or atleast we have to write 100 calls to that insert query


Now we will see how it can be achived very effectively using AOP.

Include following jars in the classpath
1)aspectjrt.jar
2)aspectjweaver.jar
3)cgilib.jar
4)aopalliance.jar
5)asm.jar

add following tag in spring configuration file ie beans.xml in our case
<aop:aspectj-autoproxy/> as follows



create a new service class to add the dependencies and name it has ApplicationService and is as below




Now write our Aspect as follows

 

now see because of the pointcut expression matched to any method inside com.kb package, our audit() method having insert query logic executes automatically without any of the call to this audit() method.

No matter how many methods will be , we can configure using pointcut and wildcard expression and we can make the call automatically without writing in any code in any of the method.

Now run the main program as below


output will be as follows






 Observe that after user registration audit is called and after login also audit aspect is called automatically.

Thanks for Reading.