Using More Than One Database Server in hibernate

During the development of a complex application, you may need to connect to more than one database
server. This requirement typically arises when you’re developing a replacement application for a legacy
system. The legacy applications has its own database servers, and you may have another one. The new
application code must communicate effectively with all the servers. Of course, you want to keep every-thing
working with Hibernate, so you must have a way to communicate with multiple database servers.
Fortunately, this isn’t a big deal to Hibernate, because it’s all in the configuration file(s). When you
instantiate a Configuration object, the system will by default attempt to find either a hibernate.properties
or a hibernate.cfg.xml file in the application’s root directory. One of these files contains the database con-figuration
information needed to contact a database server. To communicate with a second database
server, you need another configuration file.
For example, let’s say we have a MySQL database and a Microsoft SQL Server database that will be used
in an application. We’ll let the hibernate.cfg.xml file contain the connection and mapping information for
the MySQL database. For the Microsoft SQL Server database, we’ll build a configuration file called
sqlserver.cfg.xml, which looks like this:
<?xml version="I.0" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 2.0//EN"
http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd>
<hibernate-configuration>
<session-factory>
<property name="connection.driver class">
com.microsoft.jdbc.Driver</property> <property name="connection.url">
jdbc.Microsoft://localhost/products</property> <property
name="username">sa</property>
<property name="password">sa</property>
</session-factory>
</hibernate-configuration>
We now have two different configuration files for our databases. Next we create an application that uses
the files. Here’s an example piece of code:
Configuration configuration = new ConfigurationO.addClass(CD.class);
SessionFactory mysqlSession = configuration.buildSessionFactoryQ;
configuration = new Configuration().
configure("sglserver.cfg.xml").addClass(CD.class);
SessionFactory sqlserverSession = configuration.buildSessionFactoryO;


This code handles two different database servers. Remember, the key to using Hibernate is the
SessionFactory built from a Configuration object. The first part of the code creates a
Configuration object and a SessionFactory object using the technique from Chapter 3. This code
uses the default hibernate.cfg.xml file for its connection and mapping information.
The trick to using multiple databases comes into play in the second part of the code. Here we build a
new Configuration object, but we use a method called configure() to bring in the SQL Server con-figuration
file. The configure() method accepts an XML document that adheres to the hibernate-con-figuration-
2.0.dtd file. Our configuration file is designed to work with hibernate-configuration-2.0.dtd;
as such, the Configuration object gladly accepts it as a valid configuration file. Subsequently, the
object ignores the default configuration file.

JDBC Database Connection in hibernate

As an experiment in how Hibernate uses a database connection, remove or rename the file hibernate
.properties, or remove the database elements in hibernate.cfg.xml (if you’re using it), in either the stand-alone
or servlet application written in the previous chapter. When you’ve changed the file, execute the
application and attempt an action that accesses the database, such as showing all the CDs. Since our
error handling displays the stack trace, you should get a fairly large trace dump on the console window
where you launched the application. If you’re using the servlet example, you might need to open a log
file to see the errors.
At the top of the stack trace, you should see a message like “user needs to supply connection”. This error
tells you that Hibernate was unable to obtain a connection to any database for more than just a wrong
password. But, in fact, no hibernate.properties file or database elements are available to the application;
as such, the application doesn’t know how to connect to a database. This is obviously bad, because
Hibernate accomplishes most of its work through a database.
The point is, the developers of Hibernate developed the system in a manner that lets you handle a vari-ety
of design situations. In this case, Hibernate can either create its own connection to the underlying
database or use a connection that’s already in place. The examples in Chapter 3 show you how to use
Hibernate connections. If you’re developing an application from scratch, you’ll probably let Hibernate
handle the connection; there aren’t any glaring issues with this type of situation, and there are no perfor-mance
problems. So, why does Hibernate allow user-based connections? Primarily to handle legacy
issues.
Given the constant evolution of software systems, you won’t always be able to rewrite your code. In
some cases, you must refactor live systems. The application has already been written, and database con-nections
are established and available, so why not use them? You need to consider a couple of issues.
The first is connection pooling, which we discuss in detail later in this chapter. If you’re using a previ-ously
established connection, you’ll bypass any connection pooling defined in Hibernate. Second is the
issue of transactions. When you’re using a user-based connection, you can use Hibernate’s transaction
system (discussed in Chapter 10), or the application can handle transactions through the underlying
database using JDBC transactions or through JTA.
Here’s an example of the code for using a previously established connection:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.
getConnection("jdbc:mysql://localhost/accounts");
SessionFactory sessionFactory = Configuration.buildSessionFactory();
Session session = sessionFactory.openSession(connection);
} catch (Exception e) {}

Why we call start() method which in turns calls run method in java, why not we directly call run method ?

In both the above examples, the run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? Because the run() method is not a regular class method. It should only be called by the JVM. Writing thread classes is not about a single sequential thread, it's about the use of multiple threads running at the same time and performing different tasks in a single program. The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. This is how the performance can be improved, and all other benefits mentioned above can be achieved.

You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller's thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. Especially for the computers have a single processor, it is impossible to run all running threads at the same time. The JVM must implement a scheduling scheme that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM.

Java serailization , transient , static concept in core java | core java interview questions

In core java interview questions, Serialization is one of the important topic in which we come across various questions like
What is Transient, Explain Serailization, What is serialversionUID, What is use of serialVersionUID, what is Serilization. (interface, class).
I have gone through various technical interview question websites and found that all answers are very short and dosent give idea of interrelated questions.

This tutorial will help beginners to understand everything related to serialization in one go.

Will first start with basic key points.
All objects in memory are exist only as long as java virtual machine running.
Serialization is process of writing objects to a stream and read from stream. Writing to a stream will make your object persistable. We can save object state on physical file system. and read it later whenever required and restore object state.
Using serialization we can maintain object state beyond java virtual machine lifetime.

Java provides mechnisam to persist the object.
Key points to use this mechanisam is. Your object should be serializable.
How can we make our object serializable? by implementing java.io.Serializble.
What about java library, system classes. Are all of them are serializable? No.
Most of the classes which makes sense to serialize are by default implementing Serializable. But some classes dosent make sense are not.
for E.g : String, Swing, AWT, Class implements Serializable.
Thread, ClassLoader, Socket, OutputStream ..dosent implement Serializable.

Key point to remember is why we need to implement Serializable explicitely? Because java.lang.Object dosent implement serializable. This facility is given to implementer.
What happens if your class is using one of the system class which is not serilizable..for e.g Thread, OutputStream?
Java provides transient keyword. (As mentioned earlier ..Making Thread serializable dosent make sense) so we can mark this member as transient and Serialization process will exclude this member from serialization.

What will be the value of transient variable when we read it back? it will be default value.. for string null.

Now we understood the concept of serialization, and what is use of transient.
Lets do simple example.
Create simple class.

package transientTest;

import java.io.Serializable;

public class TestClass implements Serializable{
 private String fName;
 public String getfName() {
  return fName;
 }
 public void setfName(String fName) {
  this.fName = fName;
 }
 public String getlName() {
  return lName;
 }
 public void setlName(String lName) {
  this.lName = lName;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 private String lName;
 private transient String  password;
}
Test the class. Write to file and read from file.
package transientTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerialization {
 public static void main(String... st) throws Exception{
  ObjectOutputStream obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
  TestClass ts= new TestClass();
  ts.setfName("Shashi");
  ts.setlName("Jadhav");
  ts.setPassword("pass");
  obj.writeObject(ts);
  obj.close();
  ObjectInputStream objin= new ObjectInputStream(new FileInputStream(new File("Test.out")));
  TestClass ts1=(TestClass)objin.readObject();
  objin.close();
  System.out.println("ts.getfName():"+ts1.getfName());
  System.out.println("ts.getlName():"+ ts1.getlName());
  // returns null: because TestClass.password is transient.
  System.out.println("ts.getPassword():"+ ts1.getPassword());
  TestClass1 ts12= (TestClass1)ts1.getTestcls();
  System.out.println("test12:"+ts12.mname);
 }
}
Looks very simple .. yes!
But we need to look at the few real time scenario.
Suppose you create the object, set the state and write to stream. In same execution you change the state of the object and try to write it again. What will be the behavior... ?
TestClass ts= new TestClass();
  ts.setfName("Shashi");
  ts.setlName("Jadhav");
  ts.setPassword("pass");
  obj.writeObject(ts);
  ts.setlName("-----");
  obj.writeObject(ts);
  obj.close();
 In above code, you have changed the lName to ---- and again wrote the same object to stream..
Key point to remember.. ObjectOutputStream maintain a reference to an object written to it. That means if the state of the object is written and then written again. the new state will not be saved.
There are two ways to do it.
use reset().
close the stream and write it once again.
obj.reset();
obj = new ObjectOutputStream(new FileOutputStream(new File("Test.out")));
obj.writeObject(ts);
obj.close();

There are few other points you need to consider is about GC. once object is written to stream. make sure that object is availble for GC.

One more key point to remember ...or consider scenario..
You have a class which is persisted, and when you try to read it ... by that time class is modified (added new member..). What will happen?
By default if your class is changed after write.. you will not be able to read it.. because your class is modified. serialization will throw exception java.io.invalidClassException().
How serialization identifies that class is modified.. ?
Best answer is ..all persistent capable classes (Implements Serializable) are automatically given a unique identifier. if the identifier of the class is \not equal to the identifier of saved object.
How to resolve this issue... ? answer is serialVersionUID.
You assign the serialVersionUID to the class which will remain same before and after modification.

Eg: Create a class using serialVersionUID.
package transientTest.readwritemodify;

import java.io.Serializable;

public class TestClass implements Serializable{
 static final long serialVersionUID= 1l;
 
 private String name;
 private String lname;
 public String getLname() {
  return lname;
 }

 public void setLname(String lname) {
  this.lname = lname;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}
Now.. even if your class is modified but the serialversionUID remains the same.. you will be able to read and write. only additioanl state you have added after modification will be set to null

How can you get serialVersionUID runtime?
use :
ObjectStreamClass.getSerialVersionUID(o.getClass());
serialver is one more utility can be used to get the class version.

What if a super class/interface implements a serializable and you dont want your implementing/extending class to provide this facility.
you can override 2 methods and throw exception.

private void writeObject(ObjectOutputStream out)throws IOException{
  throw new NotSerializableException("");
 }
 
 private void readObject(ObjectInputStream in) throws IOException{
  throw new NotSerializableException("");
 }

Binary Tree, Heap Concept Used in Java collection

A Binary Tree is made of nodes.
Each node contains left pointer and right pointer and a data element.





The root pointer points to the top most node in the tree.
Binary Search Tree (BST) or "Ordered Binary Tree" is a type of binary tree where the nodes are arranged in order for each node.
Elements in left sub tree are less ot equal to the node.
Elements in the right are greater that the node.


Binary tree has two possible branches. left and right.


Heap is complete binary tree. It is tree based datastructure.
There are two types of heap
Max Heap: Element with greatest key (value) is always in the root node.
Min Heap: Element with smallest key (value) is always in the root node.


Java 2 platform provides binary heap implementation with class PriorityQueue java collection framework.


In Java virtual machine heap (heap described above and JVM heap could be different, jvm specification does not provide such details. However the term used is same.) is the runtime data area from which memory for all class instances and array is allocated.
  • Heap is created on virtual machine startup.
  • Heap storage for objects is reclaimed by a automatic storage management system know as GC.
  • Heap is shared among all java virtual machine thread.
  • Heap is split up in to "generations"
  • "Young Generation" stores short lived objects.
  • "Old Generation" objects persist longer are stored in old generation.
  • "Permanent Generation" is used to store class definition and reflection related information and used by virtual machine itself.
  • -Xms (minimum) and -Xmx (Max) parameters are used to specify heap size.
Create Binary tree data structure in java.
package BinaryTree;

public class BinaryTreeExample {
 static class Node
 {
  Node left;
  Node right;
  int value;
  public Node(int value) {
   this.value = value;
  }
 }
 
 public void insert(Node node, int value){
  if (value < node.value) {
            if (node.left != null) {
                insert(node.left, value);
            } else {
                System.out.println("  Inserted " + value + " to left of node " + node.value);
                node.left = new Node(value);
            }
        } else if (value > node.value) {
            if (node.right != null) {
                insert(node.right, value);
            } else {
                System.out.println("  Inserted " + value + " to right of node " + node.value);
                node.right = new Node(value);
            }
        }

 }
 
 public void printInOrder(Node node) {
        if (node != null) {
            printInOrder(node.left);
            System.out.println("  Traversed " + node.value);
            printInOrder(node.right);
        }
    }

}


-----------------------------------

package BinaryTree;

public class Main {
 public static void main(String... str){
  BinaryTreeExample bnary= new BinaryTreeExample();
  BinaryTreeExample.Node node = new BinaryTreeExample.Node(50);
  bnary.insert(node, 6);
  bnary.insert(node, 20);
  bnary.insert(node, 9);
  bnary.insert(node, 9);
  bnary.insert(node, 20);
  bnary.insert(node, 14);
  bnary.insert(node, 15);
  bnary.insert(node, 22);
  bnary.printInOrder(node);
 }
}

Java Classloader concept | java class loader tutorial

Java ClassLoader

  1.     Java classloader is part of java runtime environment that dynamically loads java class in to java virtual machine.
  2.   Usually classes are loaded on demand.
  3. Java provides ClassLoader abstract class to extend class loading function.
  4.   User defined class loader should do basic functions as: Given the name of the class, a class loader attempt to locate or generate data that constitutes a definition for a class.
  5. Every class object contains reference to the classloader.

        TestLoad.class.getClassLoader()

 Class objects for Array classes are not created by class loader, but are created automatically by java runtime.
    ClassLoader uses delegation model to search for classes and resources.
    Method defineClass() converts an array of bytes in to instance of class.

cls = defineClass(className, classBytes, 0, classBytes.length);

    Various class loaders

Bootstrap Class Loader : Loads classes from JAVA_HOME/lib
Extension Class Loader (sun.misc.launcher$ExtClassLoader): Loads classes from extension directory.
System Class Loader (sun.misc.launcher$AppClassLoader): Loads classes from java.class.path.

    Methods to remember:

findClass(String name) : finds specified class
getParent(): Returns parent class loader for delegation.
getSystemClassLoader(): returns system classloader for delegation.
loadClass(): loads class with specified name.
resolveClass().

     User defined classloader needs permission to load system classes.

method to use defineClass(String name, byte[] b, int off, int len, ProtectionDomain domain).

Write custom class loader.
1) Create class which extends ClassLoader.
2) Override protected synchronized method LoadClass().
3) Use findLoadedClass() to identify if class is already loaded.
4) Handle security exception. for the system classes.
5) In case of security exception, call super.loadClass(). delegate to super classloader.
4) Create test class file.
5) Read the file as byte array.
6) Call define class method.

package classLoader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class MyClassLoader extends ClassLoader {
 private static final int BUFFER_SIZE = 8192;

 protected synchronized Class loadClass(String className, boolean resolve)
   throws ClassNotFoundException {

  // 1. is this class already loaded?
  Class cls = findLoadedClass(className);
  if (cls != null) {
   System.out.println("Class is already available..");
   return cls;
  }

  // 2. get class file name from class name
  String clsFile = className.replace('.', '/') + ".class";

  // 3. get bytes for class
  byte[] classBytes = null;
  try {
   InputStream in = getResourceAsStream(clsFile);
   byte[] buffer = new byte[BUFFER_SIZE];
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int n = -1;
   while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
    out.write(buffer, 0, n);
   }
   classBytes = out.toByteArray();
  } catch (IOException e) {
   System.out.println("ERROR loading class file: " + e);
  }

  if (classBytes == null) {
   throw new ClassNotFoundException("Cannot load class: " + className);
  }

  // 4. turn the byte array into a Class
  try {
  
   cls = defineClass(className, classBytes, 0, classBytes.length);
   if (resolve) {
    resolveClass(cls);
   }
   System.out.println("Loaded using CUSTOM class loader..:"+cls);
  } catch (SecurityException e) {
   cls = super.loadClass(className, resolve);
   System.out.println("Loaded using SYSTEM class loader..:"+cls);
  }

  return cls;
 }
}



package classLoader;

public class TestClassLoader {
 public static void main(String[] args) throws Exception {
        MyClassLoader loader1 = new MyClassLoader();
        Class testLoad = Class.forName("classLoader.TestLoad", true, loader1);
        System.out.println("TestLoad class: " + testLoad);
        if (TestLoad.class.equals(testLoad)) {
            System.out.println("TestLoad loaded through custom loader is the same as that loaded by System loader.");
        }
        else {
            System.out.println("TestLoad loaded through custom loader is NOT same as that loaded by System loader.");
        }
        java.lang.reflect.Method main = testLoad.getMethod("main",
                                                new Class[] {String[].class});
        main.invoke(null, new Object[]{ new String[]{} });
    }
}

Can you synchronize the constructor of object in Java

According to the Java language specification you can not use java synchronized keyword with constructor it’s illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it.