Tuesday, September 8, 2009

EJB and Hibernate notes

EJB

*Session Bean -- stateful and stateless
* Entity Bean
* Message Driven Bean

EJB Architecture
* A remote interface -- a client interacts with it
* A home interface -- used for creating objects and for declaring business methods
* A bean object -- an object which actually performs business logi cna EJB-specific operations
* A deployment descriptor -- ( an XML file containing all information required for maintaining the EJB) or a set of deployment desciptor.
* A primary key class - is only entity bean specific.

[http://www.comptechdoc.org/docs/kanti/ejb/ejbarchitecture.html]

Entity Bean
* represent data in the database.
* most of the time container takes care of the persistence, transaction and access control while developer can focus on the bean logic.

Container Managed Bean
* all the logic for synchronizing the bean's state with the database is handled automatically by the container.
* developer does not need to write any data access logic.
* container takes care of persistence.

Bean Managed Persistence
* developer can handle the persistence if needed.
* developer can handle the data source.

ORM
ORM is the automated persistence of objects in Java application to the tables in a relational database.

Hibernate
*persistence framework
*pure java object relational mapping.
*maps POJO to relational database tables.
*relieves developr from persistence related programming task.
*hibernate.cfg.xml - hibernate configuration file
* *.hbm.xml -- mapping file, tells which tables and columns to use to load and store objects.
*hibernate.properties - resource bundle

session
*light-weight and non-threadsafe object
*sessionFacotry creates session and then closes it once work is done.

Hibernate Persistent Class (Hibernate Bean)
* just another regular bean class.
* setters and getters, no arg constructor
* can override the equals() and hashcode() methods.
* the persistent class should not be final.

JDBC and Database related notes

JDBC Connection steps

* loading driver class - Class.ForName("driver class").newInstance();
* Connection - Connection con = DriverManager.getConnection("databaseurl","username","passwprd");
* statement - Statement stmt = con.CreateStatement();
* execute sql - stmt.executeQuery("query");
* get data from resultset - rst.getString("column_name");

Auto Commit

con.setAutoCommit(false);
.........................
.........................
(transaction statements)
.........................
.........................
con.setAutoCommit(true);

Calling Stored Procedure



CallableStatement cs = con.prepareCall("call show_supplier");
Resultset rs = cs.executeQuery();  
Warnings(SQL)

To handle sql warning connection, statement, resultset each object can invoke a method called getwarning. [con.getWarning();]

JDBC driver types

Type1:- JDBC-ODBC bridge
Type2:- Native API partly Java Driver
Type3:- Network Protocol Driver
Type4:- JDBC Net pure Java Driver

Logging JDBC

DriverManager.println();

SQL Locator
A locator is a SQL3 datatype that acts as a logical pointer to data. Used to handle- array, blob and clob data.

Transaction Isolation Level
* 4 levels
* Connection.setIsolationLevel()
* Isolation Levels
TRANSACTION_READ_UNCOMMITTED
TRANSACTOIN_READ_COMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE

Anomalies
* Dirty Reads
* Non-repeatable reads
* Phantom reads

Metadata
* two important classes : DatabaseMetaData and ResultsetMetaData
DatabaseMetaData.getImportedKeys() returns a resultset with data about foreign keys etc.


Locking
Pessimistic Locking: - good for data integrity, bad for concurrency, defensive approach, lock the data and always expect that someone can access the interim data before it gets updated.

optimistic Locking:- exptects that a clash between multiple updates to the same data will seldom occur.

batch updating
stmt.addBatch(SQL statment here);
stmt.addBatch(SQL statment here);
stmt.addBatch(SQL statment here);
................................
................................
stmt.executeBatch();
stmt.clearBatch();

Saturday, July 25, 2009

JDK and JRE version conflict: major.minor version 50.0

The error mentioned above in the post heading is a frequent arrival when different version of jdk and jre conflict. This error occurs when somebody compiles a program with higher version of javac and tries to run with lower version of jre or vice-versa.

For example:

#javac -version
javac 1.6_0_10

#java -version
java version "1.3.1_01"
java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1_01)
Java HotSpot(TM) Client VM (build 1.3.1_01, mixed mode)

Solution - Temp

1. Download Jre1.6 or whatever version same as the javac version.
2. Manually set path to the new jre.
3. open a command window and type

#set path="C:\Program Files\Java\jre1.6_0_10\bin";

3. Now, for this session of the cmd window whenever you invoke java -- new jre will be invoked.

Sunday, July 19, 2009

Hibernate

Few hibernate tutorials:

1. https://www.hibernate.org (Hibernate core and annotations downloads)
2. https://www.hibernate.org/255.html (Hibernate Eclipse Plugin)
3.https://www.hibernate.org/hib_docs/tools/viewlets/createcfgxml_viewlet_swf.html (introductory video)
4. http://www.roseindia.net/hibernate/firstexample.shtml (First example)

A simple Hibernate implementation with a POJO object. (Eclipse)

Step1:
** Create a simple Java project in eclipse.
** Configure the build path and add hibernate.jar and mysql-connector-driver.jar in it.
**Further include all the required jar files. (see the hibernate distribution and all the jar files that are in the required folder.)
** Download sl4j from http://www.slf4j.org/download.html and include any one of(and only one) slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar in the build path.
**** Be very careful not to mix different version of sl4j. Use the same version of sl4j-api.jar and any one of the above mentioned jar files. If mixed an error will occur that read:

java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory at org.slf4j.LoggerFactory.(LoggerFactory.java:60)

**
The Java build path libraries should look like:
5. Now create a JavaBean. This bean maps to a table called user which stores id, username and password information in a mysql database.

package yogidilip.tutorial;

public class HibernateBean {

private String username;
private String password;
private long id;

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}

6. Create a bean implementation class. This is the man hibernate implementation class. It uses the session factory to read the hibernate configuration file and opens the connection to the database.

package yogidilip.tutorial;


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


public class HibernateImpl {

public static void main(String[] args) throws MappingException {
Session session = null;

try{
//this step will read hibernate.cfg.xml
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
session = sessionfactory.openSession();

//Create new instance of user and set values in it by reading them from form object

System.out.println("Inserting Record");
HibernateBean user = new HibernateBean();
user.setId(7);
user.setUsername("Dilip");
user.setPassword("Rachana");
session.save(user);
/*session.beginTransaction().commit();*/
System.out.println("Done");
}
catch(Exception e){
System.out.println(e);
}
finally{
session.flush();
session.close();
}
}

}

7. Create a hibernate.cfg.xml file in the src directory. This file will contain all the database related connection information.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/User</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!--<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
--><mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>


8. The actual ORM mapping file user.hbm.xml should look like.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="yogidilip.tutorial.HibernateBean" table="USER">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>

<property name="username">
<column name="USERNAME" />
</property>
<property name="password">
<column name="PASSWORD"/>
</property>
</class>
</hibernate-mapping>

9. The mysql syntax for creating the database and table user should look like.

CREATE DATABASE User;

CREATE TABLE user (
id INT NOT NULL AUTO_INCREMENT ,
username VARCHAR( 255 ) NOT NULL ,
password VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( id )
) TYPE = INNODB;

10. To run the example the HibernateImpl.java file can be run as a regular Java program. If everything goes well you should be able to see a success message that looks like.

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Hibernate: insert into USER (USERNAME, PASSWORD, ID) values (?, ?, ?)

11. This post is a modified version of the tutorial http://www.roseindia.net/hibernate/firstexample.shtml at roseindia.net . All the credit goes to the author of the above tutorial.

Saturday, July 4, 2009

Weblogic Tutorial

Collection of some Weblogic Tutorials.

1. http://edocs.bea.com/wls/docs70/adminguide/startstop.html -- Starting and Stopping server.
2. http://egeneration.beasys.com/platform/docs81/confgwiz/index.html -- Configuring domains and templates.

Saturday, April 11, 2009

Java Interview Questions

For the past few days I have been reading a lot about probable java interview questions. Finally, I thought to share it and here is what I have got. For now I will add some fundamental questions and answers and keep the post updating as I come across more. I have tried to put the answer as brief as possible so as it would be easy to remember. Answers here are taken from different Java books one being "The Complete Reference".

Fundamentals:

class: a template for object.
object: instance of a class.
constructor: initializes an object immediately upon creation.

Data Types:
Primitive: byte, short, int, long, char, float, double, and boolean
byte:- 8 bit
short:- 16 bit
int :- 32 bit
long:- 64 bit
float:- 32 bit
double:-64 bit

char:- 16 bit; 8 bit in C/C++; represents unicode.

final variable: value never changes
final method: can't be overridden
final class: can't be extended; all methods are implicitly final

access modifiers: public, private, protected
public: accessible by any other code.
private: is not accessible outside the class.
protected: seen outside the current package, but only to classes that subclass the class directly.
default: accessible in the same package.

static: any member declared static can be accessed before any object of its class are created, and without reference to any object. If a field or method is defined as static then there is only one copy for entire class rather than one copy for each instance. Static methods cannot access non-static field or call non-static method.

static variables: usually global variables; no copy is made
static methods: can only call other static methods; must only access static dta; cannot refer to this or super.

abstract class: cannot be instansitaed but can be extended.
abstract methods: with no method body, should be inside and abstract class.
Interface: abstract class with only abstract methods.

polymorphism: one interface, multiple methods
method overloading: parameter defines the method implementation.
method overriding: in inheritance; subclass overrides the superclass's method with same signature and parameter; name and type signature hast to be same or else they will be just overloaded.

super(): calls the constructor of the superclass

Advanced Java:

finalize() : free resources captured by any Java object.

Object Serialization: Writing an object and re-constructing the same object back in the exact form is known as object serialization. Object serialization is used in Remote Method Invocation (RMI)--communication between objects via sockets and for lightweight persistence--the archival of an object for use in a later invocation of the same program which is possible through JDBC. Serialization can be done with the helo of the interface Serializable.

Serialization: mechanism by which user can save the state of an object by converting it to a byte stream.

Connection Pool: Connection pool is about an application server storing the database connection information in order to reuse it again. If there is a connection pool every time if any request is made the system does not have to create a new connection. Connection pooling is popular in web based data driven application and Enterprise applications.

Map and HashMap :- Map is an interface whereas HashMap is a class that implements Map.
Vector and ArrayList :- Vector is synchronized and Arraylist is not. whenever multiple threads are supposed to access the same instance vectors should be used else Arraylist should be used. Arraylist gives better perfromance in non-synchronized case.

Swing and AWT:- Swing has light components whereas AWT has heavy-weight components.
Java supports passing by value.
wrapper classes: specialized classes corresponding to each of the primitive data types like Integer, Character Double.

checked exceptions: checked exceptions are those that the compiler force to catch like IOException.

J2EE