Saturday, 23 November 2013

Hibernate Tutorials

                                               Hibernate 

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.Hibernate is free software that is distributed under the GNU Lesser General Public License. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns. 


Hibernate Advantages:

 1. Hibernate takes care of mapping Java classes to database tables using XML files and without writing any    line of code and manipulates Complex associations of objects of your database.

2. Provides simple APIs for storing and retrieving Java objects directly to and from the database. 

3. If there is change in Database or in any table then the only need to change XML file properties.

 4. Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.

 5. Hibernate does not require an application server to operate.
Hibernate supports almost all the major RDBMS. Following is list of few of the database engines supported by Hibernate.
 1. HSQL Database Engine 
2.DB2
3. MySQL
 4. PostgreSQL
 5. FrontBase
 6. Oracle
 7. Microsoft SQL Server Database
 8. Sybase SQL Server
 9. Informix Dynamic Server 

 Hibernate supports a variety of other technologies, including the following: 
1.XDoclet Spring
 2.J2EE 
3. Eclipse plug-ins
 4.Maven

The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.



Downloading Hibernate:
 It is assumed that you already have latest version of Java is installed on your machine. Following are the simple steps to download and install Hibernate on your machine.
 1. Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.
 2. Download the latest version of Hibernate Click Here To Download

All SQL Queries

 Top 30 SQL QUERIES


1. AND / OR

SELECT column_name(s)
FROM table_name
WHERE condition
AND|OR condition

2. ALTER TABLE
ALTER TABLE table_name
ADD column_name datatype
or
ALTER TABLE table_name
DROP COLUMN column_name
 
3. AS (alias)
SELECT column_name AS column_alias
FROM table_name
or
SELECT column_name
FROM table_name  AS table_alias
4. BETWEEN
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
5.CREATE DATABASE
CREATE DATABASE database_name 
6.CREATE TABLE
CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
...
)
7.CREATE INDEX
CREATE INDEX index_name
ON table_name (column_name)
or
CREATE UNIQUE INDEX index_name
ON table_name (column_name)
8.CREATE VIEW


CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
9.DELETE

DELETE FROM table_name
WHERE some_column=some_value
or
DELETE FROM table_name
( Deletes the entire table)
DELETE * FROM table_name
(  Deletes the entire table)

10.DROP DATABASE


 DROP DATABASE database_name


11.DROP INDEX

DROP INDEX index_name (MySQL)
12.DROP TABLE

DROP TABLE table_name
13.GROUP BY
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
14.HAVING
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
15.IN

SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,value3..)
16.INSERT INTO


INSERT INTO table_name
VALUES (value1, value2,....)
or
INSERT INTO table_name
(column1, column2,...)
VALUES (value1, value2,....)
17.INNER JOIN


SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
18.LEFT JOIN

SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
19.RIGHT JOIN

SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
20.FULL JOIN
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
22.LIKE
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
23.ORDER BY
SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
24.SELECT

SELECT column_name(s)
FROM table_name
25.SELECT *

SELECT *
FROM table_name
26.SELECT DISTINCT
SELECT DISTINCT column_name(s)
FROM table_name
27.SELECT INTO
SELECT *
INTO new_table_name

 FROM old_table_name
or
SELECT column_name(s)
INTO new_table_name

 FROM old_table_name
28.SELECT TOP

SELECT TOP number|percent column_name(s)
FROM table_name


29.TRUNCATE TABLE

 TRUNCATE TABLE table_name
30.UNION

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
31.UNION ALL

SELECT column_name(s) FROM table_name1
UNION ALL 
SELECT column_name(s) FROM table_name2
32.UPDATE

UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
33.WHERE
SELECT column_name(s)
FROM table_name
WHERE column_name operator value

Data Types in C

In  C programming language, data types are used for declaring variables and functions.The type of a variable determines how much space it takes in storage and how the bit pattern stored is interpreted.
C Programming
C Programming


The data types in C can be classified as follows:
1. Basic Types:   
   They are arithmetic types and are of the two types: (a) integer types and (b) floating-point types.
2.Enumerated types:
 They are also arithmetic types and they are used to define variables that can   only be    assigned  certain discrete integer values throughout the program.
3.The type void:
 The type specifier void indicates the no value .
4.Derived types:
 They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types  and (e) Function types.
The array types and structure types are  the aggregate  data types. The data type of a function specifies the type of  function's return value.The  basic  data types  are in the following section

Integer Types:

Following table shows you details about standard integer types with its storage sizes and value ranges:

Type          Storage size Value range
char                 1 byte        -128 to 127 or 0 to 255
unsigned char 1 byte         0 to 255
signed char      1 byte         - 128 to 127
int                   2 or 4 byte   -32,768 to 32,767 or -2,147,483,648 to 2,147,483,648
unsigned int     2 or 4 bytes   0 to 65,535 or 0 to 4,294,967,296
short                2 bytes          32,768 to 32,765
unsigned short 2 bytes          0 to 65,536
long                  4 bytes         -2,147,483,648 to 2,147,483,646
unsigned long   4 bytes            0 to 4,294,967,294

To get the size of the a variable on a particular platform, we can use the sizeof function. The sizeof(type) yields the storage size of the object or type in bytes.Example

#include <stdio.h>
#include <limits.h>

int main()
{
   printf("Storage size for int : %d \n", sizeof(int));
   
   return 0;
}
 result on Linux:

Storage size for int : 4


Floating-Point Types:

Following table shoes you details about standard floating-point types with  sizes , ranges and their precision:

Type             Storagesize  Value range                 Precision
float               4 byte             1.2E-38 to 3.4E+38       6 decimal places
double           8 byte  2.3E-308 to 1.7E+308    15 decimal places
long double     10 byte         3.4E-4932 to 1.1E+4932  19 decimal places
The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs.

#include <stdio.h>
#include <float.h>

int main()
{
   printf("Storage size for float : %d \n", sizeof(float));
   printf("Minimum float positive value: %E\n", FLT_MIN );
   printf("Maximum float positive value: %E\n", FLT_MAX );
   printf("Precision value: %d\n", FLT_DIG );
   
   return 0;
}
After  compilation , it produces the following result on Linux:

Storage size for float : 4
Minimum float positive value: 1.175493E-38
Maximum float positive value: 3.402823E+38
Precision value: 6


The void Type:  

Following table shoes you details about the void type.
1.Function returns as void:
  A function with no return value has the return type as void.
  For example void exit (int status);
2.Function arguments as void:
   A function with no parameter . For example, int example(void);
3.Pointers to void:
A pointer of type void  represents the address , but not its  type.
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments

Variables In C

A variable is a name given to a storage area . Each variable in C has a type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
c programming
c programming


The name of a variable is a identifier . It must begin with a letter or an underscore. Based on the basic types explained in previous post, there will be the following basic variable types:

Type      Description
char        Typically a single character. This is an integer type.
int        The most natural size of integer for the machine.
float         A single-precision  value.
double A double-precision  value.
void          Represents the absence of type.

C programming language also permits to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc.

Variable Definition in C:

A variable definition is a way to tell the compiler where and how much to create the storage for the variable. A variable definition contain a data type and contains a list of one or more variables of that type as follows:

    type variable_list;

Here, type must be a valid C data type including char,  int, float, user-defined object, double or a bool etc., and variable_list may has one or more than one identifier names.for example:

 int    a, b, c;
 char   cr, af;
 float  g, salary;
 double h;
The line int a, b, c; both declares and defines the variables a, b and c; which instructs the compiler to create variables named a, b and c of type int.

Variables can be initialized (assigned an initial value) in  declaration. The initialization consists of an equal sign followed by a constant expression .

type variable_name = value;
Some examples are:

extern int d = 3, f = 5;    // declaration of d and f.
int d = 3, f = 5;           // definition and initializing d and f.
byte z = 22;                // definition and initializes z.
char x = 'x';               // the variable x has the value 'x'.

For definition without an initialization: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.

Variable Declaration in C:

Declaration of a  variable  provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without checking complete detail about the variable. A declaration has its meaning  only for   compilation time, compiler use this  variable declaration at the time of linking of the program.

A variable declaration is more efficient  when you are using multiple files .You define a variable in one of the files which will be available at the time of linking of the program. You can use extern keyword to declare a variable at any place.
Example
Try the example,

#include <stdio.h>

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main ()
{
  /* variable definition: */
  int a, b;
  int c;
  float f;

  /* actual initialization */
  a = 10;
  b = 20;
  
  c = a + b;
  printf("value of c : %d \n", c);

  f = 70.0/3.0;
  printf("value of f : %f \n", f);

  return 0;
}
The  output is :

value of c : 30
value of f : 23.333334

Same concept is applied on a function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere in the program.

// function declaration
int func();

int main()
{
    // function call
    int i = func();
}

// function definition
int func()
{
    return 0;
}

Lvalues and Rvalues in C:

C has  two kinds of expressions i:

lvalue : An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.

rvalue : An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned.The valid statement is:

int g = 20;

But following will generate compile-time error:
10 = 20;
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments

Friday, 22 November 2013

c Basic Syntax

The basic structure of C programming is easy and it will be help full to understand other building blocks of the C programming language.
C Programming
C Programming


Tokens:

A token in c programming is either a keyword, an identifier, a constant, a string literal, or a symbol.
For example,
the following statements of a c program consist  five tokens:
printf("Hey, World! \n");
The five tokens are:
1.printf
2.(
3."Hey, World! \n"
4.)
5.;

Semicolons(;)

The semicolon is a statement terminator in a c program.
Each statement in c must be ended with a semicolon.

For example,the two different statements:
1.printf("Hey, World! \n");
2.return 0;
each statement is ended with a semicolon.

Comments:

Comments helps to easily understand your C program and they are not compile by the compiler.
They start with /* and terminates with the characters */ as shown below:

/* c program for print hello */
You cannot have comments within comments.

Identifiers:

A identifier is a name used to identify a variable, function, or any other user-defined item.
An identifier would be start with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).
the followimg symbols cannot be used within identifiers .@, $, and % .

Here are some examples of acceptable identifiers:

mohd       zara    abc   move_name  a_123
myname50   _temp   j     a23b9      retVal

Keywords:

The following list shows the reserved words in C. These reserved words may not be used as constant or variable or any other identifier names.

auto       else        long       switch
break    enum    register                typedef
case       extern  return   union
char       float       short     unsigned
const     for          signed   void
continue              goto       sizeof    volatile
default if             static     while
do           int           struct    _Packed
double
C - Overview
C - Basic Syntax
C - Data Types
C - Variables
C - Constants
C - Storage Classes
C - Operators
C - Decision Making
C - Loops
C - Functions
C - Scope Rules
C - Arrays
C - Pointers
C - Strings
C - Structures
C - Unions
C - Bit Fields
C - Typedef
C - Input & Output
C - File I/O
C - Preprocessors
C - Header Files
C - Type Casting
C - Error Handling
C - Recursion
C - Variable Arguments
C - Memory Management
C - Command Line Arguments

Thursday, 21 November 2013

Insertion In Red Black Tree

Insertion In Red Black Tree:
There are three Cases for inserting  a node in Red Black Tree.1.Find the correct leaf to insert new node instead of it
2.Color node in red, and attach 2 black leafs to it
3.Make sure RB-tree properties hold



Insertion in red-black tree
Insertion in red-black tree
Case 1: a’s uncle (d) is red:
1.Color a’s father (b) and uncle (d) black
2.Color a’s father (c) red


Insertion in red-black tree
Insertion in red-black tree
   
Case 2: a’s uncle is black, a is a right child
1. Rotate left around a’s father (b)
2.Continue to case 3



Case 3: a’s uncle is black, a is a left child:
1. Rotate right around a’s grandfather (c)
2. Switch colors between a’s father (b)
and a’s (new) sibling (c)

Insertion in red-black tree
Insertion in red-black tree

Red Black Tree

Red-black tree is a Binary search tree that has each node is colored either red or black.
Properties of red black tree:
1. This is the same as for binary search trees: all the keys
     to left of a node are smaller, and a to the right of a node are
     larger than the node key
2.The number of black nodes on every path from the root
     to each leaf is the same.  This is called as the black height of the tree.
3. No two consecutive nodes are red.
Red Black Tree
Red Black Tree

 Red Black tree ensure that the longest path from the root to a leaf is at most twice as long as the shortest path.  Since insertion and searching  in a binary search tree have time proportional to the length of
the path from the root to the leaf, this is sure that O(log(n)) times for these
operations, even if the  red black tree is not perfectly balanced.

Tuesday, 27 August 2013

Wrapper class



Wrapper class

Wrapper class were a solution of the primitive data type not being a part of object oriented approach of java….like being returned from a method as a method.
Java allows you to include the primitives in the family of objects by using what are called wrapper classes
There is a wrapper class for every primitive in java.. the wrapper class for int is Integer, for float is Float.
The wrapper classes in the Java API serve two primary purposes:
  • To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
  • To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.
The wrapper object of a wrapper class can be created in one of two ways: by instantiating the wrapper class with the new operator or by invoking a static method on the wrapper class.
Creating wrapper object with new operator
Primitive datatype-->Wrapper Class-->Constructor arguments
  • boolean--> Boolean--> boolean or String
  • byte--> Byte--> byte or String
  • char--> Character--> char
  • short--> Short--> short or String
  • int-->Integer--> int or String
  • long--> Long--> long or String
  • float-->Float--> float double or String
  • double-->Double--> double or String
All the wrapper classes are declared final. That means you cannot derive a subclass from any of them.All the wrapper classes except Boolean and Character are subclasses of an abstract class called Number, whereas Boolean and Character are derived directly from the Object class.All of the wrapper classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String representation of the type being constructed.
Boolean wboo = new Boolean("false");
Boolean yboo=new Boolean(false);
Character c1 = new Character('c');
Note that there is no way to modify a wrapped value—that is, the wrapped values are immutable. To wrap another value, you need to create another object.

WRAPPING PRIMITIVES USING A STATIC METHOD
All wrapper classes offers static valueOf() methods which give you another approach to creating wrapper objects. Because it's a static method, it can be invoked directly on the class (without instantiating it), and will return the corresponding object that is wrapping what you passed in as an argument.
this method  take a String representation of the appropriate type of primitive as its first argument, it also takes an additional argument, int radix, which indicates in what base (for example binary, octal, or hexadecimal) the first argument is represented
Integer i2 = Integer.valueOf("101011", 2);  // converts 101011 to 43 and assigns the
                                           // value 43 to the Integer object i2

USING WRAPPER CONVERSION UTILITIES
xxxValue() method
When you need to convert the value of a wrapped numeric to a primitive, use one of the many xxxValue() methods. All of the methods in this family are no-arg methods. Each of the six numeric wrapper classes has six methods, so that any numeric wrapper can be converted to any primitive numeric type.
Integer i2 = new Integer(42);  //  make a new wrapper object
byte b = i2.byteValue();         //  convert i2's value to a byte primitive
short s = i2.shortValue();      //  another of Integer's xxxValue methods
double d = i2.doubleValue(); //  yet another of Integer's xxxValue methods

xxx Parsexxx(String) method
If you do not need to store a value in a wrapper but just want to convert the type , you can do it by using an appropriate static method of the appropriate wrapper class. For example, all the wrapper classes except Character offer a static method that has the following signature:
static <type> parse<Type>(String s)
The <type> may be any of the primitive types except char (byte, short, int, long, float, double, or boolean), and the <Type> is the same as <type> with the first letter uppercased;
String s = "123";
int i = Integer.parseInt(s);


parseXxx() and valueOf()
·  parseXxx() returns the named primitive.
·  valueOf() returns a newly created wrapped object of the type that invoked the method.
double d4 = Double.parseDouble("3.14");     // convert a String to a primitive
System.out.println("d4 = " + d4);               // result is  "d4 = 3.14"
Double d5 = Double.valueOf("3.14");         // create a Double object
System.out.println(d5 instanceof Double ); // result is "true"

toString() method
All of the wrapper classes have a no-arg, nonstatic, instance version of toString(). This method returns a String with the value of the primitive wrapped in the object—
Double d = new Double("3.14");
System.out.println("d = " + d.toString() );    //  result is "d = 3.14"
All of the numeric wrapper classes provide an overloaded, static toString() method that takes a primitive numeric of the appropriate type (Double.toString() takes a double), and, of course, returns a String with that primitive’s value.
System.out.println("d = " + Double.toString(3.14);    // result is "d = 3.14"
Integer and Long provide a third toString() method. It is static, its first argument is the appropriate primitive, and its second argument is a radix. The radix argument tells the method to take the first argument (which is radix 10 or base 10 by default), and convert it to the radix provided, then return the result as a String
System.out.println("hex = " + Long.toString(254,16); // result is "hex = fe"

toXxxString() method(Binary, Hexadecimal, Octal)
The Integer and Long wrapper classes let you convert numbers in base 10 to other bases. These conversion methods, toXxxString(), take an int or long, and return a String representation of the converted number,
String s3 = Integer.toHexString(254);       // convert 254 to hex
System.out.println("254 in hex = " + s3);   // result is "254 in hex = fe"
String s4 = Long.toOctalString(254);        // convert 254 to octal
System.out.println("254 in octal = "+ s4);  // result is "254 in octal = 376"
Quick review
  • Java uses primitive types, such as int, char, double to hold the basic data types supported by the language.
  • Sometimes it is required to create an object representation of these primitive types.
  • These are collection classes that deal only with such objects. One needs to wrap the primitive type in a class.
  • To satisfy this need, java provides classes that correspond to each of the primitive types. Basically, these classes encapsulate, or wrap, the primitive types within a class.
  • Thus, they are commonly referred to as type wrapper. Type wrapper are classes that encapsulate a primitive type within an object.
  • The wrapper types are Byte, Short, Integer, Long, Character, Boolean, Double, Float.
These classes offer a wide array of methods that allow to fully integrate the primitive types into Java’s object hierarchy.

Wrapper classes for converting simple types

Simple Type
Wrapper class
boolean
Boolean
char
Character
double
Double
float
Float
int
Integer
long
Long

Converting primitive numbers to Object numbers using constructor methods

Constructor calling
Conversion Action
Integer IntVal = new Integer(i);
Primitive integer to Integer object
Float FloatVal = new Float(f);
Primitive float to Float object
Double DoubleVal = new Double(d);
Primitive double to Double object
Long LongVal = new Long(l);
Primitive long to Long object

NOTE : I, f, d and l are primitive data values denoting int, float, double and long data types. They may be constants or variables.

Converting Object numbers to Primitive numbers using typeValue() method

Method calling
Conversion Action
int i = IntVal.intValue();
Object to primitive integer
float f = FloatVal.floatValue();
Object to primitive float
double d = DoubleVal.doubleValue();
Object to primitive double
long l = LongVal.longValue();
Object to primitive long

Converting Numbers to Strings using toString() method

Method calling
Conversion Action
str = Integer.toString(i);
Primitive integer i to String str
str = Float.toString(f);
Primitive float f  to String str
str = Double.toString(d);
Primitive double d to String str
str = Long.toString(l);
Primitive long l to String str

Converting String Object in to Numeric Object using static method ValueOf()

Method calling
Conversion Action
IntVal = Integer.ValueOf(str);
Convert String into Integer object
FloatVal = Float.ValueOf(str);
Convert String into Float object
DoubleVal = Double.ValueOf(str);
Convert String into Double object
LongVal = Long.ValueOf(str);
Convert String into Long object

Converting Numeric Strings to Primitive numbers using Parsing method

Method calling
Conversion Action
int i = Integer.parseInt(str);
Converts String str into primitive integer i
long l = Long.parseLong(str);
Converts String str into primitive long l

NOTE : parseInt() and parseLong() methods throw a Number Format Exception if the value of the str does not represent an integer.