set PATH=%PATH%;d:\tools\jdk1.7.0_67\bin javac helloworld.java java helloworld
Add option -g in javac:
javac -g
add debug option in tag javac of build.xml debug=“true”:
<javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath" debug="true"/>
try { } catch(Exception e) { e.printStackTrace(); }
We can put try catch in some case below:
Java Editor
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.
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
Data Type | Default Value (for fields) |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | '\u0000' |
String (or any object) | null |
boolean | false |
byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings; float anArrayOfFloats[];
String strCards = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]"; // strCards from the Python script String[] byteValues = strCards.substring(1, strCards.length() - 1).split(","); byte[] cards = new byte[byteValues.length]; for (int i=0, len=bytes.length; i<len; i++) { cards[i] = Byte.parseByte(byteValues[i].trim()); }
int[][] multi = new int[5][10];
… which is a short hand for something like this:
int[][] multi = new int[5][]; multi[0] = new int[10]; multi[1] = new int[10]; multi[2] = new int[10]; multi[3] = new int[10]; multi[4] = new int[10];
Note that every element will be initialized to the default value for int, 0, so the above are also equivalent to:
int[][] multi = new int[][]{ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
refer: https://docs.oracle.com/javase/tutorial/collections/interfaces/index.html
package oata; import java.util.*; public class TestList { public static void main(String[] args) { System.out.println("Hello, World"); TestList.test1(); } public static void test1(){ List<Double> testList=new ArrayList(); testList.add(0.5); testList.add(0.2); testList.add(0.9); testList.add(0.1); testList.add(0.1); testList.add(0.1); testList.add(0.54); testList.add(0.71); testList.add(0.71); testList.add(0.71); testList.add(0.92); testList.add(0.12); testList.add(0.65); testList.add(0.34); testList.add(0.62); Collections.sort(testList); System.out.print(testList); } }
output:
Hello, World [0.1, 0.1, 0.1, 0.12, 0.2, 0.34, 0.5, 0.54, 0.62, 0.65, 0.71, 0.71, 0.71, 0.9, 0.92]
package oata; import java.util.*; class Card { private int Id; public Card() { super(); this.Id = 52; } public int GetNumber() { return this.Id / 4 + 3; } public int GetSuit() { return this.Id % 4; } public int getType() { return this.Id / 4; } public int getShape() { return this.Id % 4; } public int getId() { return this.Id; } public void setId(int param1) { this.Id = param1; } } public class TestList { public static void main(String[] args) { System.out.println("Hello, World"); TestList.test2(); } public static void test2() { List<Card> _lstCards = new ArrayList<Card>(); Card _tmpCard = new Card(); _tmpCard.setId(3); _lstCards.add(_tmpCard); _tmpCard = new Card(); _tmpCard.setId(5); _lstCards.add(_tmpCard); _tmpCard = new Card(); _tmpCard.setId(4); _lstCards.add(_tmpCard); System.out.println(); System.out.println("********Test2********"); System.out.println("Before Sort:"); for (int i = 0; i < _lstCards.size(); i++) { System.out.println(_lstCards.get(i).getId()); } System.out.println("After Sort:"); Comparator<Card> cmp = new Comparator<Card>() { @Override public int compare(Card o1, Card o2) { // TODO Auto-generated method stub int cmpval = o1.getId() - o2.getId(); return cmpval; } }; List<Card> lst = new ArrayList<Card>(_lstCards); Collections.sort(lst, cmp); for (int i = 0; i < lst.size(); i++) { System.out.println(lst.get(i).getId()); } } }
output:
********Test2******** Before Sort: 3 5 4 After Sort: 3 4 5
public static void test3(){ List<Card> _lstCards = new ArrayList<Card>(); Card _tmpCard = new Card(); _tmpCard.setId(3); _lstCards.add(_tmpCard); _tmpCard = new Card(); _tmpCard.setId(5); _lstCards.add(_tmpCard); _tmpCard = _lstCards.get(0); _tmpCard.setId(6); for (int i = 0; i < _lstCards.size(); i++) { System.out.println(_lstCards.get(i).getId()); } }
output:
6 5
refer: http://www.tutorialspoint.com/java/java_strings.htm compare 2 strings:
boolean equalsIgnoreCase(String anotherString) int compareTo(String anotherString)
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; } }
import java.util.Random; /** * Returns a pseudo-random number between min and max, inclusive. * The difference between min and max can be at most * Integer.MAX_VALUE - 1. * * @param min Minimum value * @param max Maximum value. Must be greater than min. * @return Integer between min and max, inclusive. * @see java.util.Random#nextInt(int) */ public static int randInt(int min, int max) { // NOTE: This will (intentionally) not run as written so that folks // copy-pasting have to think about how to initialize their // Random instance. Initialization of the Random instance is outside // the main scope of the question, but some decent options are to have // a field that is initialized once and then re-used as needed or to // use ThreadLocalRandom (if using at least Java 1.7). Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; }
Because rand.nextInt(value) return random Interteger between 0 and value
import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive ThreadLocalRandom.current().nextInt(min, max + 1);
import java.util.HashMap; import java.security.MessageDigest; public static String md5(String original) { try{ MessageDigest md = MessageDigest.getInstance("MD5"); md.update(original.getBytes()); byte[] digest = md.digest(); StringBuffer sb = new StringBuffer(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); }catch(Exception e){ return ""; } }
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
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.
refer links:
{ "person":{"name":"Sam", "surname":"ngonma"}, "car":{"make":"toyota", "model":"yaris"} }
We can update JSON Object
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person"); person.put("name", "Sammie");
private void updateJson(JSONObject mapChannels, int i){ String channelId = Integer.toString(i); String bets = m_channels.get(i).getBets(); String betsAdvange = m_channels.get(i).getBetsAdvange(); JSONObject channelObj = mapChannels.getJSONObject(channelId); channelObj.put("bets", JSON.parseArray(bets)); channelObj.put("betsAdvange", JSON.parseArray(betsAdvange)); mapChannels.put(channelId, channelObj); } public String channels2Json(){ JSONObject returnObj = new JSONObject(); JSONObject objChannels = new JSONObject(); objChannels.put("maxChannel", m_channels.size()); for(int i = 0; i < m_channels.size(); i++) { Channel channel = m_channels.get(i); objChannels.put(Integer.toString(i), channel); updateJson(objChannels, i); } returnObj.put("Channel", new JSONObject(objChannels)); return returnObj.toJSONString(); }
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!
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!
(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.
public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } }
public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); }
refer: https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html
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:
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); } }
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"); } }
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; } } }
javac DemoExecutor.java
run:
java DemoExecutor
refer:
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:
<property name="hibernate.connection.pool_size">100</property>
refer: http://hibernate.org/tools/ Install:(You must use Eclipse 3.6 to install Hibernate tool)
mvn archetype:generate -DgroupId=hibernate.tutorials -DartifactId=hibernate -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
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; } }
<?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
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(); } } }
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) );
<?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”/>
<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:
mvn compile mvn exec:java -Dexec.mainClass="hibernate.tutorials.ManageEmployee"
<?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>
First, we need to create object SesstionFactory:
factory = new Configuration().configure().buildSessionFactory();
/* 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(); } }
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:
@Entity @Table(name = "stock_transaction", catalog = "mkyong") @org.hibernate.annotations.Entity( dynamicInsert = true ) public class StockTransaction implements java.io.Serializable {
<class ... table="stock_transaction" catalog="mkyong" dynamic-insert="true"> <id name="tranId" type="java.lang.Integer"> <column name="TRAN_ID" /> <generator class="identity" /> </id>
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:
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); for ( int i=0; i<100000; i++ ) { Customer customer = new Customer(.....); session.save(customer); if ( i % 20 == 0 ) { //20, same as the JDBC batch size //flush a batch of inserts and release memory: session.flush(); session.clear(); } } tx.commit(); session.close();
Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); ScrollableResults customers = session.getNamedQuery("GetCustomers") .setCacheMode(CacheMode.IGNORE) .scroll(ScrollMode.FORWARD_ONLY); int count=0; while ( customers.next() ) { Customer customer = (Customer) customers.get(0); customer.updateStuff(...); if ( ++count % 20 == 0 ) { //flush a batch of updates and release memory: session.flush(); session.clear(); } } tx.commit(); session.close();
refer:
Steps by steps to use reverseengineering tool in eclipse:
refer:
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
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:
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):
SET GLOBAL MAX_CONNECTIONS = 200;
MAX_CONNECTIONS = 200
<property name="hibernate.connection.pool_size">100</property>
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.
refer:
public interface ConnectionProvider A strategy for obtaining JDBC connections. Implementors might also implement connection pooling. The ConnectionProvider interface is not intended to be exposed to the application. Instead it is used internally by Hibernate to obtain connections. void close() Release all resources held by this provider. void closeConnection(Connection conn) Dispose of a used connection. void configure(Properties props) Initialize the connection provider from given properties. Connection getConnection() Grab a connection, with the autocommit mode specified by hibernate.connection.autocommit. boolean supportsAggressiveRelease() Does this connection provider support aggressive release of JDBC connections and re-acquistion of those connections (if need be) later? This is used in conjunction with org.hibernate.cfg.Environment.RELEASE_CONNECTIONS to aggressively release JDBC connections.
import javax.sql.DataSource; import com.mchange.v2.c3p0.DataSources; ..... public class C3P0ConnectionProvider implements ConnectionProvider, Configurable, Stoppable, ServiceRegistryAwareService { ..... private DataSource ds; @Override public Connection getConnection() throws SQLException { final Connection c = ds.getConnection(); ..... @Override public void configure(Map<String, Object> props) { ..... final DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl, connectionProps ); ds = DataSources.pooledDataSource( unpooled, allProps ); ..... @Override public void stop() { try { DataSources.destroy( ds ); } catch (SQLException sqle) { C3P0_MSG_LOGGER.unableToDestroyC3p0ConnectionPool( sqle ); } }
With Datasources from c3p0 source https://github.com/swaldman/c3p0/blob/master/src/java/com/mchange/v2/c3p0/DataSources.java
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:
<property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.max_statements">1000</property>
refer: http://books.zkoss.org/wiki/Setup_MySQL_DB_in_Eclipse
slf4j-api-1.7.12.jar
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
commons-lang3-3.4.jar
import org.apache.commons.lang3.*
Eclipse build errors - java.lang.object cannot be resolved. Fix:
Eclipse build errors - java.lang.UnsupportedClassVersionError ⇒ Seems like you are using JDK8 for compiling and Lower version for running it. Fix:
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.
Fix: In Hibernate Configuration, remove the session-factory name. Try using only
<session-factory> <!-- ... --> </session-factory>
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: 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×tamp=1513743122935&hash=d5ae896e9bda2f1f8d14da4f2f437091 ⇒ fix: import the certificate of site to keystore lib\security\cacerts:
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