Table of Contents

Java

refer:

Create simple code and run

  1. Step1: create helloworld.java:
    public class helloworld { 
      public static void main(String[] args) { 
        System.out.println("Hello, World");
      }
    }
  2. Step2: run on windows
    set PATH=%PATH%;d:\tools\jdk1.7.0_67\bin
    javac helloworld.java
    java helloworld

Debug in java

Build debug with command line

Add option -g in javac:

javac -g

Build debug with ant

add debug option in tag javac of build.xml debug=“true”:

<javac srcdir="${src.dir}" destdir="${classes.dir}"  classpathref="classpath" debug="true"/>

Debug in code with try catch

try
{
}
catch(Exception e)
{
    e.printStackTrace();
}

We can put try catch in some case below:

refer: https://github.com/google/gson

Config Tab to space in eclipse editor

Java Editor

  1. Click Window » Preferences
  2. Expand Java » Code Style
  3. Click Formatter
  4. Click the Edit button
  5. Click the Indentation tab
  6. Under General Settings, set Tab policy to: Spaces only
  7. Click OK to apply the changes.

Java Platforms

Java 32bits and 64bits

refer: http://howtodoinjava.com/for-fun-only/difference-between-32-bit-java-vs-64-bit-java/

Which versions of java you should install on 32-bit/64-bit machines?

Can a .class file generated using a 32-bit java compiler be used on 64-bit java?

Absolutely Yes.:

If so, then how 32-bit applications run on 64-bit systems?Answer is that 64-bit systems include a compatibility layer called WoW64, which actually switches the processor back and forth between 32-bit and 64-bit modes depending on which thread needs to execute; making 32-bit software run smoothly even in the 64-bit environment.

Java application on Windows and Linux

Some java application developed with own native libraries. With these own native libraries, they were diffrent in windows and linux. For example: native libraries in windows with extension were .ddl and in linux with extension were .so in windows

Java Syntax

Java Data Types

Java Primitive Data Types

Data TypeDefault Value (for fields)
byte0
short0
int0
long0L
float0.0f
double0.0d
char'\u0000'
String (or any object) null
booleanfalse

Java Arrays

Java Collection with List

refer: https://docs.oracle.com/javase/tutorial/collections/interfaces/index.html

Convert Array to List

Integer[] spam = new Integer[] { 1, 2, 3 };
Arrays.asList(spam);

Java String

refer: http://www.tutorialspoint.com/java/java_strings.htm compare 2 strings:

boolean equalsIgnoreCase(String anotherString)
int compareTo(String anotherString)

Java Map

refer: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html

Java Static Methods, Variables, Static Block and Class with Example

refer: http://crunchify.com/java-static-methods-variables-static-block-and-class-with-example/ The static keyword can be used in 3 scenarios:

Example:

package com.crunchify.tutorials;
 
/**
 * @author Crunchify.com
 */
 
public class CrunchifyStaticDeclaration {
 
	// 1st static block 
	static {
		System.out.println("\nI'm static block 1..");
		setTestString("This is static block's String");
		setTestValue(2);
	}
 
	// 2nd static blocks in same class
	static {
		System.out.println("\nI'm static block 2..");
	}
 
	// static variable example
	private static int testValue; // kept private to control it's value through setter
 
	public int getTestValue() {
		return testValue;
	}
 
	// static method example
	public static void setTestValue(int testValue) {
		if (testValue > 0)
			CrunchifyStaticDeclaration.testValue = testValue;
		System.out.println("setTestValue method: " + testValue);
	}
 
	public static String testString;
 
	/**
	 * @return the testString
	 */
	public static String getTestString() {
		return testString;
	}
 
	/**
	 * @param testString the testString to set
	 */
	public static void setTestString(String testString) {
		CrunchifyStaticDeclaration.testString = testString;
		System.out.println("setTestString method: " + testString);
	}
 
	// static util method
	public static int subValue(int i, int... js) {
		int sum = i;
		for (int x : js)
			sum -= x;
		return sum;
	}
}

Advance Java

Random in Java

Java Reflection

refer: https://docs.oracle.com/javase/tutorial/reflect/member/index.html

Java ClassLoader

refer: http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html

In Java, a class is identified by its fully qualified class name. The fully qualified class name consists of the package name and the class name. But a class is uniquely identified in a JVM using its fully qualified class name along with the instance of the ClassLoader that loaded the class. Thus, if a class named Cl in the package Pg is loaded by an instance kl1 of the class loader KlassLoader, the class instance of C1, i.e. C1.class is keyed in the JVM as (Cl, Pg, kl1). This means that the two class loader instances (Cl, Pg, kl1) and (Cl, Pg, kl2) are not one and the same, and classes loaded by them are also completely different and not type-compatible to each other

Java Json

refer:

Data types of Json in Json Data(refer http://www.json.org/):

JsonObject, JsonArray, JsonString, and JsonNumber are subtypes of JsonValue. These are constants defined in the API for null, true, and false JSON values.

Java json org

Java Fast Json

refer links:

Some Basic Examples

Concurrency

refer: https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

Java Threads Objects

refer: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

Provide a Runnable object

The Runnable interface defines a single method run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

public class HelloRunnable implements Runnable {
 
    public void run() {
        System.out.println("Hello from a thread!");
    }
 
    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }
 
}

output:

Hello from a thread!

Subclass Thread

The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:

public class HelloThread extends Thread {
 
    public void run() {
        System.out.println("Hello from a thread!");
    }
 
    public static void main(String args[]) {
        (new HelloThread()).start();
    }
}

output:

Hello from a thread!

Synchronization

(Only in case application with Multithread(Not single application)) refer:https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html

Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.

High level Concurrency Objects

refer: https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html

Thread pools

refer:

Thread pools address two different problems:

public class ThreadPoolExecutor extends AbstractExecutorService {
.......................
    private static int workerCountOf(int c)  { return c & CAPACITY; }
    private static boolean isRunning(int c) {
        return c < SHUTDOWN;
    }
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }
.......................

Example for Thread Pool: with 100 tasks, we want to run them using ideally 10, and maximum 20 threads:

  1. Step1: Create new thread DemoThread.java:
    public class DemoThread implements Runnable
    {
        private String name = null;
     
        public DemoThread(String name) {
            this.name = name;
        }
     
        public String getName() {
            return this.name;
        }
     
        @Override
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Executing : " + name);
        }
    }
  2. Step2: Create new thread pool CustomThreadPoolExecutor.java
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
     
    public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
     
        public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
                long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        }
     
        @Override
        protected void beforeExecute(Thread t, Runnable r) {
            super.beforeExecute(t, r);
            System.out.println("Perform beforeExecute() logic");
        }
     
        @Override
        protected void afterExecute(Runnable r, Throwable t) {
            super.afterExecute(r, t);
            if (t != null) {
                System.out.println("Perform exception handler logic");
            }
            System.out.println("Perform afterExecute() logic");
        }
     
    }
  3. Step3:Create application DemoExecutor.java excute thread pool
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.RejectedExecutionHandler;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
     
    public class DemoExecutor
    {
        public static void main(String[] args)
        {
            Integer threadCounter = 0;
            BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(50);
     
            CustomThreadPoolExecutor executor = new CustomThreadPoolExecutor(10,
                                                20, 5000, TimeUnit.MILLISECONDS, blockingQueue);
     
            executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r,
                        ThreadPoolExecutor executor) {
                    System.out.println("DemoTask Rejected : "
                            + ((DemoThread) r).getName());
                    System.out.println("Waiting for a second !!");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Lets add another time : "
                            + ((DemoThread) r).getName());
                    executor.execute(r);
                }
            });
            // Let start all core threads initially
            executor.prestartAllCoreThreads();
            while (true) {
                threadCounter++;
                // Adding threads one by one
                System.out.println("Adding DemoTask : " + threadCounter);
                executor.execute(new DemoThread(threadCounter.toString()));
     
                if (threadCounter == 100)
                    break;
            }
        }
     
    }
  4. Step4: Compile and run
    javac DemoExecutor.java

    run:

    java DemoExecutor

Hibernate

refer:

Hibernate Application Architecture

refer: http://www.tutorialspoint.com/hibernate/hibernate_architecture.htm

High level view of the Hibernate Application Architecture:

Detailed view of the Hibernate Application Architecture with few important core classes:

Install Hibernate Tools

refer: http://hibernate.org/tools/ Install:(You must use Eclipse 3.6 to install Hibernate tool)

Simple Application with Hibernate

refer: http://www.tutorialspoint.com/hibernate/hibernate_quick_guide.htm

Phase1: Create Simple Code using Hibernate

  1. Step1: Using maven to create project hibernate with package hibernate.tutorials:
    mvn archetype:generate -DgroupId=hibernate.tutorials -DartifactId=hibernate -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
  2. Step2: Create java POJO class Employee.java(A POJO (Plain Old Java Object) is a Java object that doesn't extend or implement some specialized classes and interfaces respectively required by the EJB framework)
    package hibernate.tutorials;
    public class Employee {
       private int id;
       private String firstName; 
       private String lastName;   
       private int salary;  
     
       public Employee() {}
       public Employee(String fname, String lname, int salary) {
          this.firstName = fname;
          this.lastName = lname;
          this.salary = salary;
       }
       public int getId() {
          return id;
       }
       public void setId( int id ) {
          this.id = id;
       }
       public String getFirstName() {
          return firstName;
       }
       public void setFirstName( String first_name ) {
          this.firstName = first_name;
       }
       public String getLastName() {
          return lastName;
       }
       public void setLastName( String last_name ) {
          this.lastName = last_name;
       }
       public int getSalary() {
          return salary;
       }
       public void setSalary( int salary ) {
          this.salary = salary;
       }
    }
  3. Step3: Create Mapping Configuration File for table EMPLOYEE that instructs Hibernate how to map the defined class or classes to the database tables. You should save the mapping document in a file with the format <classname>.hbm.xml(employee.hbm.xml)(save the file to directory src\main\java\hibernate\tutorials\:
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
     "-//Hibernate/Hibernate Mapping DTD//EN"
     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
     
    <hibernate-mapping>
       <class name="hibernate.tutorials.Employee" table="EMPLOYEE">
          <meta attribute="class-description">
             This class contains the employee detail. 
          </meta>
          <id name="id" type="int" column="id">
             <generator class="native"/>
          </id>
          <property name="firstName" column="first_name" type="string"/>
          <property name="lastName" column="last_name" type="string"/>
          <property name="salary" column="salary" type="int"/>
       </class>
    </hibernate-mapping>

    option class name=“hibernate.tutorials.Employee” ⇒ Must be Full name of Class as hibernate.tutorials.Employee, not name Employee. Fix error below

    sessionFactory object.org.hibernate.MappingException: entity class not found
  4. Step4: Create Application Class ManageEmployee.java
    package hibernate.tutorials;
    import java.util.List; 
    import java.util.Date;
    import java.util.Iterator; 
     
    import org.hibernate.HibernateException; 
    import org.hibernate.Session; 
    import org.hibernate.Transaction;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
     
    public class ManageEmployee {
       private static SessionFactory factory; 
       public static void main(String[] args) {
          try{
             factory = new Configuration().configure().buildSessionFactory();
          }catch (Throwable ex) { 
             System.err.println("Failed to create sessionFactory object." + ex);
             throw new ExceptionInInitializerError(ex); 
          }
          ManageEmployee ME = new ManageEmployee();
     
          /* Add few employee records in database */
          Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
          Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
          Integer empID3 = ME.addEmployee("John", "Paul", 10000);
     
          /* List down all the employees */
          ME.listEmployees();
     
          /* Update employee's records */
          ME.updateEmployee(empID1, 5000);
     
          /* Delete an employee from the database */
          ME.deleteEmployee(empID2);
     
          /* List down new list of the employees */
          ME.listEmployees();
       }
       /* Method to CREATE an employee in the database */
       public Integer addEmployee(String fname, String lname, int salary){
          Session session = factory.openSession();
          Transaction tx = null;
          Integer employeeID = null;
          try{
             tx = session.beginTransaction();
             Employee employee = new Employee(fname, lname, salary);
             employeeID = (Integer) session.save(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
          return employeeID;
       }
       /* Method to  READ all the employees */
       public void listEmployees( ){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             List employees = session.createQuery("FROM Employee").list(); 
             for (Iterator iterator = 
                               employees.iterator(); iterator.hasNext();){
                Employee employee = (Employee) iterator.next(); 
                System.out.print("First Name: " + employee.getFirstName()); 
                System.out.print("  Last Name: " + employee.getLastName()); 
                System.out.println("  Salary: " + employee.getSalary()); 
             }
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
       /* Method to UPDATE salary for an employee */
       public void updateEmployee(Integer EmployeeID, int salary ){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             Employee employee = 
                        (Employee)session.get(Employee.class, EmployeeID); 
             employee.setSalary( salary );
    		 session.update(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
       /* Method to DELETE an employee from the records */
       public void deleteEmployee(Integer EmployeeID){
          Session session = factory.openSession();
          Transaction tx = null;
          try{
             tx = session.beginTransaction();
             Employee employee = 
                       (Employee)session.get(Employee.class, EmployeeID); 
             session.delete(employee); 
             tx.commit();
          }catch (HibernateException e) {
             if (tx!=null) tx.rollback();
             e.printStackTrace(); 
          }finally {
             session.close(); 
          }
       }
    }

Phase2: Config Hibernate connect MySQL Database

  1. Step1: Create database test and table EMPLOYEE with sql script below:
    CREATE TABLE EMPLOYEE (
       id INT NOT NULL AUTO_INCREMENT,
       first_name VARCHAR(20) DEFAULT NULL,
       last_name  VARCHAR(20) DEFAULT NULL,
       salary     INT  DEFAULT NULL,
       PRIMARY KEY (id)
    );
  2. Step2: Create hibernate.cfg.xml in directory src\main\java\
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-configuration SYSTEM 
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
     
    <hibernate-configuration>
       <session-factory>
       <property name="hibernate.dialect">
          org.hibernate.dialect.MySQLDialect
       </property>
       <property name="hibernate.connection.driver_class">
          com.mysql.jdbc.Driver
       </property>
     
       <!-- Assume test is the database name -->
       <property name="hibernate.connection.url">
          jdbc:mysql://localhost/test
       </property>
       <property name="hibernate.connection.username">
          root
       </property>
       <property name="hibernate.connection.password">
          root123
       </property>
     
       <!-- List of XML mapping files -->
       <mapping resource="hibernate/tutorials/Employee.hbm.xml"/>
     
    </session-factory>
    </hibernate-configuration>

    which contain mapping xml for table Employee: <mapping resource=“hibernate/tutorials/Employee.hbm.xml”/>

Phase3: Config build and run

  1. Step1: Add options in pom.xml
    <project>
    .......
      <build>
        <resources>
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>**/*.xml</include>
            </includes>
          </resource>
        </resources>
      </build>
    .......
      <dependencies>
    .......
        <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-core</artifactId>
          <version>4.3.10.Final</version>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.6</version>
        </dependency>
      </dependencies>
    .......
    </project>

    Explain options for compiling with maven:

    • Resource directory which contain xml configs: resources
    • Using dependency hibernate-core, mysql-connector-java
  2. Step2: Build and Run:
    mvn compile
    mvn exec:java -Dexec.mainClass="hibernate.tutorials.ManageEmployee"

Hibernate Config encoding UTF8

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="cardfactory">
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">xxxxx</property>
        <property name="hibernate.connection.url">jdbc:mysql:///cardgame?useUnicode=true;characterEncoding=utf-8</property>
        <property name="hibernate.connection.CharSet">utf8</property>
        <property name="hibernate.connection.characterEncoding">utf8</property>
        <property name="hibernate.connection.useUnicode">true</property>
        <property name="current_session_context_class">thread</property>
    </session-factory>
</hibernate-configuration>

With options for encoding UTF-8:

<property name="hibernate.connection.url">jdbc:mysql:///cardgame?useUnicode=true;characterEncoding=utf-8</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>

Some basic query functions in Hibernate

First, we need to create object SesstionFactory:

factory = new Configuration().configure().buildSessionFactory();

Custom query functions in Hibernate

Config Hibernate insert sql defaul values

refer: http://www.mkyong.com/hibernate/hibernate-dynamic-insert-attribute-example/

You can configure the dynamic-insert=“true” properties value through annotation or XML mapping file:

Hibernate Batch processing

http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch15.html

A naive approach to inserting 100,000 rows in the database using Hibernate might look like this:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    session.save(customer);
}
tx.commit();
session.close();

⇒ This would fall over with an OutOfMemoryException somewhere around the 50,000th row. That is because Hibernate caches all the newly inserted Customer instances in the session-level cache. In below example, we will show you how to avoid this problem:

First set the property:

hibernate.jdbc.batch_size 20

And use batch scripts below:

Custom Configure

refer: http://docs.jboss.org/hibernate/orm/4.2/manual/en-US/html/ch03.html#configuration-optional

Hibernate map editor

Hibernate reverseengineering tool

refer:

Steps by steps to use reverseengineering tool in eclipse:

  1. Step1: Create Hibernate configuration file(hibernate.cfg.xml) for project: right click project name → New → Hibernate Configuration File(.cfg.xml)
    with some basic informations below:
    • database name: test
    • username: admin
    • password: admin12!@
  2. Step2: Create Hibernate Console Configuration: A Console configuration describes how the Hibernate plugin should configure Hibernate and what configuration files and classpaths are needed to load the POJO's, JDBC drivers etc. It is required to make use of query prototyping, reverse engineering and code generation
  3. Step3: view Hibernate Console Configuration created from Step2. Go to window→show view→Hibernate Configurations
  4. Step4: Create configuration for Hibernate code generator
  5. Step5: Config Main for Hibernate code generator
    • Check option Reverse engineer from JDBC Connection
    • And enter package name, for example: vn.casino.entities
  6. Step6: Config Export for Hibernate code generator: Check 2 options Domain Code and Hibernate XML Mappings: Note: You add option Hibernate XML Configuration to generate hibernate.cfg.xml
  7. Step7: Click Run to generate java code and Hibernate XML Mappings

Hibernate Foreign key Using XML mapping

refer:

Hibernate log

You need to config display log for package org.hibernate with log4j to check hibernate log

# org.hibernate FileAppender
log4j.appender.hibernateAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.hibernateAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.hibernateAppender.File=logs/cardgameExt/hibernate.log
log4j.appender.hibernateAppender.layout.ConversionPattern=%d{dd MMM yyyy | HH:mm:ss,SSS} | %-5p | %t | %c{3} | %3x | %m%n
log4j.appender.hibernateAppender.Encoding=UTF-8
log4j.appender.hibernateAppender.DatePattern='.'yyyy-MM-dd
log4j.category.org.hibernate=INFO,consoleAppender,hibernateAppender

Java Connection Pool

Connection pooling is the technique used to increase the performance of the application when an Connection pooling takes care of managing connections(prepare,open and close)

refer:

Default Hibernate connection pooling

Below are basic steps config for connections in Hibernate(each connection in MySQL was a session in Hibernate)(refer: https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/configuration-hibernatejdbc.html):

  1. Config max connections in MySQL:
    • config temporary in MySQL Admin console:
      SET GLOBAL MAX_CONNECTIONS = 200;
    • config in my.cnf or my.ini of MySQL:
      MAX_CONNECTIONS = 200
  2. Config max pool connections:
    <property name="hibernate.connection.pool_size">100</property>
  3. coding to close session after call(in doWork() function):
    public class DBConnection {
        private static SessionFactory factory;
        static {
            factory = new Configuration().configure().buildSessionFactory();
        }
        public Session getSession() {
            return factory.openSession();
        }
     
        public void doWork() {
            Session session = getSession();
            // do work.
            session.close();
        }
        // Call this during shutdown
        public static void close() {
            factory.close();
        }
    }

Most important Hibernate JDBC properties:

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">secret</property>
<property name="hibernate.connection.url">jdbc:mysql:///cardgame?useUnicode=true;characterEncoding=utf-8</property>
<property name="hibernate.connection.pool_size">1</property>

⇒ Hibernate's internal connection pooling algorithm is rudimentary, and is provided for development and testing purposes. Use a third-party pool for best performance and stability. To use a third-party pool, replace the hibernate.connection.pool_size property with settings specific to your connection pool of choice. This disables Hibernate's internal connection pool.

org.hibernate.connection.C3P0ConnectionProvider with c3p0 connection pool

refer:

Download jar for using hibernate c3p0:

Hibernate uses its org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider for connection pooling if you set the hibernate.c3p0.* properties. properties.

<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> 
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">2000</property>
<property name="hibernate.c3p0.max_statements">1000</property>

⇒ You need to turn on hibernate log to check debug log and error log when using c3p0 pool Some basic pool configuration in hibernate-c3p0:

Using external libraries for coding java with eclipse

Install JDBC driver for eclipse

refer: http://books.zkoss.org/wiki/Setup_MySQL_DB_in_Eclipse

  1. Step1: Download and Install MySQL Connector from http://dev.mysql.com/downloads/connector/j/. MySQL Connector will be installed to directory C:\Program Files (x86)\MySQL\MySQL Connector J
  2. Step2: Using Eclipse to choose the data resources for MySQL Connection via [Window]/[Show View]/[Data Management]/[Data Source Explorer]

Using slf4j

Using commons.apache

Fix java errors

Eclipse build errors - java.lang.object cannot be resolved

Eclipse build errors - java.lang.object cannot be resolved. Fix:

Eclipse build errors - java.lang.UnsupportedClassVersionError

Eclipse build errors - java.lang.UnsupportedClassVersionError ⇒ Seems like you are using JDK8 for compiling and Lower version for running it. Fix:

  1. Step1: Install jdk 1.6
  2. Step2: Go to Window > Preferences > Java > Compiler > compiler level change Compiler Compliance level to 1.6. Then change configure at bottom of dialog point to path of jdk1.6

Hibernate error procedure can't return a result set in the given context

Hibernate call procedure error:

procedure can't return a result set in the given context

Because the jar required for the MySQL DB connectivity was old. Simply upgrade this jar version(MySQL-Connector) to mysql-connector-java-5.1.12-bin.jar and exception gets removed.

Hibernate error HHH000277: Could not bind factory to JNDI

Fix: In Hibernate Configuration, remove the session-factory name. Try using only

<session-factory>
   <!-- ... -->
</session-factory>

java.lang.UnsupportedClassVersionError : Unsupported major.minor version 52.0

java.lang.UnsupportedClassVersionError: java.lang.UnsupportedClassVersionError Unsupported major.minor version 52.0

⇒ You get this error because a Java 7 VM tries to load a class compiled for Java 8 (Java 8 has the class file version 52.0 but a Java 7 VM can only load class files up to version 51.0)

The issue is because of Java version mismatch. Referring to the Wikipedia Java Class Reference :

These are the assigned major numbers. The error regarding the unsupported major.minor version is because during compile time you are using a higher JDK and a lower JDK during runtime.

Thus, the 'major.minor version 52.0' error is possibly because the jar was compiled in jdk 1.8, but you are trying to run it using a jdk 1.7 environment. The reported number is the required number, not the number you are using. To solve this, it's always better to have the jdk and jre pointed to the same version.

javax.net.ssl.SSLHandshakeException

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target, requestUri = https://plf.kingvip.us/api/game/user_register?username=anhvclk&password=123456&timestamp=1513743122935&hash=d5ae896e9bda2f1f8d14da4f2f437091 ⇒ fix: import the certificate of site to keystore lib\security\cacerts:

  1. Step1: Go to https://system.kybai.tv and save the certificate to file kybai.cer
  2. Step2: import the kybai.cer to keystore
    keytool -import -alias kybai -file kybai.cer -keystore d:\tools\SmartFoxServer_2X\jre\lib\security\cacerts

    (the password of keystore default “changeit” or blank)

And check if your certificate is already in the truststore by running the following command:

keytool -list -keystore d:\tools\SmartFoxServer_2X\jre\lib\security\cacerts

with password blank