Thursday 14 February 2013

Hibernate Mapping Explanation

Hibernate Mapping

<hibernate-mapping> </hibernate-mapping> The mapping document is an XML document having <hibernate-mapping> as the root element which contains two <class> elements corresponding to each class.

<class name="Employee" table="EMPLOYEE">
<class name="Employee" table="EMPLOYEE"> </class>  used to define specific mappings from a Java classes to the database tables.
name attribute of the class element
  table attributeof database table name
........................
</meta>
It's a optional .can be used to create class description
<id>
<id>
</id>
<id> element maps the unique ID attribute in class to the primary key of the database table.
name attribute used to id element refers to the property in the class.
column attribute used to id element refers to the column in the table.
type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
<generator>
<generator>
This element within id element.Hibernate generator element generates the primary key for new record.
It's used to generate the unique identifier for the object s of persistent class.
class attribute of generator element
class attribute of generator element
The following are the list of main generators we are using in the hibernate framework
column attribute used to id element refers to the column in the table.
  • all-delete-orphan


<meta attribute="class-description">
  • assigned
  • increment
  • sequence
  • identify
  • hilo
  • sqqhilo
  • native
  • foregin
  • uuid
  • guid
  • select
  • sequence -identity
assigned

  • This generator supports in all the databases
  • This is the default generator class used by the hibernate, if we do not specify <generator –> element under id element then hibernate by default assumes it as “assigned”

  • If generator class is assigned, then the programmer is responsible for assigning the primary key value to object which is going to save into the database

Increment

  • This generator supports in all the databases.
  • This generator is used for generating the id value for the new record by using the formulaMax of id value in Database + 1.
  • if we manually assigned the value for primary key for an object, then hibernate doesn’t considers that value.
Sequence:
  • Not support mySql
  • Database is dependent.we cannot use all database.we should know whether support or not.
  • While inserting new record in a database ,hibenate get next value from the sequence under assigns that value for the new record.
  • The programmer has created a sequence int database the name shoud passed as the generator

<id name=”employeeId” column=”empid”>
<generator>
<param name=”sequence”>mysequence</param>
</generator>
</id>
Note:above example we set mysequence value 2 new record inserted into second row
  • If the programmer has not passed any sequence name, then hibernate creates its own sequence with name “Hibernate-Sequence” and gets next value from that sequence, and than assigns that id value for new record.
  • If hibernate want’s to create its own sequence, in hibernate configuration file,hbm2ddl.auto property must be set enabled

identity
  • Database is dependent,not working in Oracle
  • identity generator is similar to increment generator, but the difference was increment generator is database independent and hibernate uses a select operation for selecting max of id before inserting new record
  • But in case of identity, no select operation will be generated in order to insert an id value for new record by the hibernate
hilo
  • Databse independent.
  • First record inserted id value as 1, for second record 32768,or the next records the id value will be incremented by 32768 and will stores into the database (i mean adds to the previous).
  • This hibernate stores the count of id values generated in a column of separated table, with name “hibernate_unique_key” by default with the column name “next_hi”.

native

  • when we use this generator class, it first checks whether the database supports identify or not, if not checks for sequence and if not, then hilo will be used finally the order will be..
    • sequence
    • identify
    • hilo
forign
  • It uses the id of another associated object,mostly use with ono-to-one relationship.
<property>
</property>
The property element used to map the class into database table .
name attribute used to id element refers to the property in the class.
type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.
<set>

<set> element is new here and has been introduced to set the relationship between two class.

cascade

  • Main concept of hibernate relations is to getting the relation between parent and child class objects Cascade attribute is mandatory, when ever we apply relationship between objects, cascade attribute transfers operations done on one object onto its related child objects
Cascade having the values…….
  • none (default)
  • save
  • update
  • save-update
  • delete
  • all
if we write cascade = “all” then all operations like insert, delete, update at parent object will be effected to child object also
Example: if we apply insert(or update or delete) operation on parent class object, then child class objects will also be stored into the database.
all-delete-orphan means, breaking relation between objects not deleting the objects from the database,if a child record is removed from the collection and if we want to remove that child record immediately from the database, then we need to set the cascade =”all-delete-orphan”.

name:
name attribute is set to the defined Set variable in the parent class.
Key:
holds the foreign key to the parent object 



Wednesday 16 January 2013

JSTL ans Servlet in Tomcat 7


JSTL in  Servlet Tomcat 7

   Tomcat 7 does not come with JSTL jar files by default.
   First, locate the jar files for both JSTL API and JSTL Implementation. They are located on the JSP Standard Tag Library download page. Click into each repository and find the .jar file.
   
Tomcat 7
           =>Servlet -api-3.0
           =>JSTL-1.2

  Servlet
             Download Servlet -api-3.0
   JSTL
        JSTL API jar - javax.servlet.jsp.jstl-api-1.2.1.jar. 
        JSTL Implementation jar -javax.servlet.jsp.jstl-1.2.1.jar. 
       Download both file in JSP standard Tag Library
               OR
         Download JSTL-1.2.jar
 After download jar file past that file into /WEB-INF/lib
Now create a simple JSP page that uses one of the JSTL Tag Libraries.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Show Account List</title>
</head>
<body>
<c:if test="${not empty allAccountList}">
<table style="width="100%" border="1" cellpadding="2" cellspacing="2" style="background-color: #ffffff;" >
<th>Account Number</th>
<th>Customer Name</th>
<th>Current Balance</th>
<th>Maximum Balance</th>
<th>Account Type</th>
<th>Account Pin</th>
<c:forEach var="accountList" items="${allAccountList}">
<tr>
<td>${accountList.accountNumber_}</td>
<td>${accountList.customerName_}</td>
<td>${accountListt.accountBalance_}</td>
<td>${accountList.accountMaximumBalance_}</td>
<td>${accountList.accountType_}</td>
<td>${accountList.accountPin}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>

web.xml   
Note: Not compulsory for that modification in web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0"> 

  <!-- Define servlets that are included in-->


 <!-- servlet mappings s>



</web-app>

Friday 11 January 2013

Insert data in database in batches using Java JDBC


  executeBatch- JDBC

In this note, we will see how we can use JDBC APIs like Statement andPreparedStatement to insert data in any database in batches.
              Also we will try to explore scenarios where we can run out of memory and how to optimize the batch operation.
Firs how Insert data in database in batches using Java JDBC.

Bad Code

String [] queries = {
    "insert into employee (name, city, phone) values ('A', 'X', '123')",
    "insert into employee (name, city, phone) values ('B', 'Y', '234')",
    "insert into employee (name, city, phone) values ('C', 'Z', '345')",
};
             
Connection connection = new getConnection();
Statement statemenet = connection.createStatement();
             
for (String query : queries) {
    statemenet.execute(query);
}
statemenet.close();
connection.close();

This is the BAD code. You are executing each query separately. This hits the database for each insert statement. Consider if you want to insert 1000 records. This is not a good idea. We’ll below is the basic code to perform batch insert. Check it out:

Good Code

Connection connection = new getConnection();
Statement statemenet = connection.createStatement();
 
for (String query : queries) {
    statemenet.addBatch(query);
}
statemenet.executeBatch();

statemenet.close();
connection.close();

        we used addBatch() method of Statement, instead of directly executing the query. And after adding all the queries we executed them in one go using statement.executeBatch() method.
             Note that we have taken the queries from a String array. Instead you may want to make it dynamically. For example:

import java.sql.Connection; Nothing fancy, just a simple batch insert.
import java.sql.Statement;
//...
Connection connection = new getConnection();
Statement statemenet = connection.createStatement();
for (Employee employee: employees) {
    String query = "insert into employee (name, city) values('"
            + employee.getName() + "','" + employee.getCity + "')";
    statemenet.addBatch(query);
}
statemenet.executeBatch();
statemenet.close();
connection.close();


Wednesday 26 December 2012

Naming Conventions


Java Naming Conventions

Packages: 

Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
     package mycalculator 

Classes: 
Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
   class Customer
   class Account 
Interfaces:
 Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:
   interface Comparable
   interface Enumerable 
Note that some programmers like to distinguish interfaces by beginning the name with an "I":
   interface IComparable
   interface IEnumerable 
Methods: 
Names should be in mixed case. Use verbs to describe what the method does:
   void calculateTax()
    string getSurname() 
Variables: 
Names should be in mixed case. The names should represent what the value of the variable represents:
   string firstName
   int orderNumber 
Constants: Names should be in uppercase.
   static final int DEFAULT_WIDTH
   static final int MAX_HEIGHT 
Private:
Camel Case and prefix private variable with a “_”

Java Packages


Java Packages


JAVA API PACKAGES

         The Java API is the set of classes included with the Java Development Environment. These classes are written using the Java language and run on the JVM. The Java API includes everything from collection classes to GUI classes
         Java interfaces and classes are grouped into packages. The following are the java packages, from which you can access interfaces and classes, and then fields, constructors, and methods.
Java API packages
java.lang
Package that contains essential Java classes, including numerics, strings, objects, compiler, runtime, security, and threads. This is the only package that is automatically imported into every Java program.
java.io
Package that provides classes to manage input and output streams to read data from and write data to files, strings, and other sources.
java.util
Package that contains miscellaneous utility classes, including generic data structures, bit sets, time, date, string manipulation, random number generation, system properties, notification, and enumeration of data structures.
java.net
Package that provides classes for network support, including URLs, TCP sockets, UDP sockets, IP addresses, and a binary-to-text converter.
java.awt
Package that provides an integrated set of classes to manage user interface components such as windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and text fields. (AWT = Abstract Window Toolkit)
java.awt.image
Package that provides classes for managing image data, including color models, cropping, color filtering, setting pixel values, and grabbing snapshots.
java.awt.peer
Package that connects AWT components to their platform-specific implementations (such as Motif widgets or Microsoft Windows controls).
java.applet
Package that enables the creation of applets through the Applet class. It also provides several interfaces that connect an applet to its document and to resources for playing audio.

Friday 21 December 2012

Error Solving


JDBC - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver Solution


  Error:

    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)


   Solution:



    Download  mysql-connector jar file from here:http://dev.mysql.com/downloads/connector/j/
       Extract that file get mysql-connector-java-5.1.22-bin.jar 

      i) Paste that file in:/usr/lib/jvm/java-6-openjdk/jre/lib
                         and :/usr/lib/jvm/java-6-openjdk/jre/lib/ext    
                                           (or)         
      ii)Paste that file in:/usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib
                         and :/usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/ext



Warning


when compile my java coding i got below warning:
            Note: PurchaseDetails.java uses unchecked or unsafe operations.
           Note: Recompile with -Xlint:unchecked for details.

Solution:
   This comes up in Java 5 and later if you're using collections without type specifiers (e.g., Arraylist()instead of ArrayList<String>()). It means that the compiler can't check that you're using the collection in a type-safe way, using generics.To get rid of the warning, just be specific about what type of objects you're storing in the collection. So, instead of

List myList = new ArrayList();
use

List<String> myList = new ArrayList<String>();