Thursday, October 2, 2008

"contact.hbm.xml" and "hibernate.cfg.xml"





Discuss the Hibernate Example - part 1

(Keep in memory to add relevant libraries for this project-libraries for hibernate 3 and MySql connecter)

Insert record for Mysql database thru hibernate but for part 1 not use hibernate query language and use session object for save data to Database table.

In this example no need to create table for transaction if we use “ update” in hibernate.hbm.xml File then it is automatically created the table shown as contact.hbm.xml Table name.

1.First we need to create connecton poolwhich is used for connecting database server and add mapping resources (see Configuring Hibernate).

2.Create POJO class with relevant data filed with to be saved in Table.
(see Writing First Persistence Class)

3.Set mapping between created POJO class data base Table(see Mapping the Contact Object to the Database Contact table)

4.Finally test hibernate example (see Developing Code to Test Hibernate example)

Configuring Hibernate
Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.


"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">




com.mysql.jdbc.Driver


jdbc:mysql://localhost/hibernatetutorial

root

10
true
org.hibernate.dialect.MySQLDialect
update





Writing First Persistence Class
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for
Contact.java:
package xx.xxx.hibernate;


public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;

public String getEmail() {
return email;
}

public String getFirstName() {
return firstName;
}


public String getLastName() {
return lastName;
}


public void setEmail(String string) {
email = string;
}


public void setFirstName(String string) {
firstName = string;
}

public void setLastName(String string) {
lastName = string;
}

public long getId() {
return id;
}

public void setId(long l) {
id = l;
}



Mapping the Contact Object to the Database Contact table
The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. Here is the code for contact.hbm.xml:


"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">



















Developing Code to Test Hibernate example
Now we are ready to write a program to insert the data into database. We should first understand about the Hibernate's Session. Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file. Then the save method on session object is used to save the contact information to the database:
Here is the code of FirstExample.java
package roseindia.tutorial.hibernate;

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

public class FirstExample {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;

try{
// This step will read hibernate.cfg.xml
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
tx = session.beginTransaction();

Contact contact = new Contact();
contact.setId(111);
contact.setFirstName("Suresh");
contact.setLastName("Rangana");
contact.setEmail("sureshpdn@yahoo.com");

session.save(contact);
tx.commit();//write to table

}catch(Exception e){
System.out.println(e.getMessage());
tx.rollback();

}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();

}

}
}

Friday, August 29, 2008

Session2 :Log4j Examples

How to use log4j for you application ….
Try with following example(for running following example you need jar file)

First see main class

public class Main {

/** Creates a new instance of Main */
public Main() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Sample sample = new Sample();
sample.doLogging();
}

}


Now see Sample class which has doLogging();

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
*
* @author Administrator
*/
public class Sample {
Logger logger = Logger.getLogger(Sample.class.getName());

Logger logger1 = Logger.getLogger("Logger1");

/** Creates a new instance of Sample */
public Sample() {
}

public void doLogging() {
logger.debug("Test Logging logger1 DEBUG");
logger.info("Test Logging logger1 INFO");
logger.warn("Test Logging logger1 WARN");
logger.error("Test Logging logger1 ERROR");
logger.fatal("Test Logging logger1 FATAL");

logger1.debug("Test Logging logger1 DEBUG");
logger1.info("Test Logging logger1 INFO");
logger1.warn("Test Logging logger1 WARN");
logger1.error("Test Logging logger1 ERROR");
logger1.fatal("Test Logging logger1 FATAL");
}
}


Lets see” log4j.properties” file
Here two appenders(X and Y ) for ConsoleAppender and RollingFileAppender you can specify conversionPattern(This show patten for logging) as preferd(Ex: %d %C{2} %l %c %m %n)

The syntax for configuring the root logger is:
log4j.rootLogger=[level], appenderName, appenderName, ...

This syntax means that an optional level can be supplied followed by appender names separated by commas.
The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or a custom level value. A custom level value can be specified in the form level#classname.

log4j.properties file

log4j.rootLogger = All,X
# Logger1 is a customLogger
log4j.logger.Logger1 = INFO,Y


log4j.appender.X=org.apache.log4j.ConsoleAppender
log4j.appender.X.layout=org.apache.log4j.PatternLayout
log4j.appender.X.layout.conversionPattern=%p %d %C{2} %l %c %m %n

log4j.appender.Y=org.apache.log4j.RollingFileAppender
log4j.appender.Y.layout=org.apache.log4j.PatternLayout
log4j.appender.Y.layout.conversionPattern=%p--%d - %C{2} - %l - %c %m %n
log4j.appender.Y.threshold=All
log4j.appender.Y.append=true
log4j.appender.Y.MaxFileSize=1KB
log4j.appender.Y.File=C:/Log.out


Try with above Example
END

Wednesday, August 27, 2008

java code for Autoboxing/Unboxing of Wrappers and Foreach and Generics

java code for Autoboxing/Unboxing of Wrappers

import java.util.List;
import java.util.LinkedList;

public class WorkOut1 {
private void test(final Integer[] intArray){
List myIntList = new LinkedList();

for (Integer integer : intArray) {
double dRandval = Math.random()*100;
Double dRandValWrapper = dRandval;//inboxing
myIntList.add(dRandValWrapper.intValue() + integer);

}

for (Integer integer : myIntList) {
System.out.println("Value : " +integer);
}

}

public static void main(String[] args) {
WorkOut1 workOut1 = new WorkOut1();
workOut1.test(new Integer[]{4,5,2,8,6,3,9,2});

}

}
--------------------------------------------------------------------------
Foreach and Generics

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;

public class WorkOut1 {
private void test(final Integer[] intArray){
List myIntList = new LinkedList();

for (Integer integer : intArray) {

Double dRandValWrapper =Math.random()*100;
myIntList.add(dRandValWrapper.intValue() + integer);

}

for (Integer integer : myIntList) {
System.out.println("Value : "+integer);
}

List ls = new ArrayList();


}

void printCollection(Collection c){

for (Object object : c) {
System.out.println(object);
}

}
// Collection c =new ArrayList();

public static void main(String[] args) {
WorkOut1 workOut1 = new WorkOut1();
//workOut1.test(new Integer[]{4,5,2,8,6,3,9,2});
List ls = new ArrayList();
ls.add("aaaa1");
ls.add("aaaa2");
ls.add("aaaa3");
ls.add("aaaa4");

workOut1.printCollection(ls);

}

}