Defining Dialect in Hibernate

MySQL Dialect
MySQL Dialect

<!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>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">pass</property>
        
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        
        <!-- Name of the Annotated Entity class -->
        <mapping class="com.mugil.dto.UserDetails"/>
    </session-factory>
</hibernate-configuration>

If hbm2ddl.auto is set to create the table will be created every time when java class is Run.The old records will be deleted.

<property name="hbm2ddl.auto">create</property>

When set to update the records will be added without new table creation

<property name="hbm2ddl.auto">update</property>

More Annotations

3

@Transient tells not to create Column
@Column tells the Hibernate the Name under which column need to be
created in Db table.

@Transient 
@Column (name="User_Name") 
private String userName; 

@Temporal tells the option of selective addition.Below I am adding Date rather than
Date & time as Timestamp

 @Temporal (TemporalType.DATE) 
 private Date DOJ;

@Lob – Large Object, Telling Hibernate to create Large Object Datatype fro Column
@Lob over String creates CLOB
@Lob over Byte creates BLOB

 @Lob
 private String userDescription;

Simple Hibernate Table Creation from Scratch

Hibernate Required Jar Files List
Hibernate Required Jar Files List

Step1: Create a Bean for which Table should be created in Database
Step2: Create a Class which uses the bean.

Step 1

package com.mugil.dto;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity 
public class UserDetails {
	@Id	
	private int userId;
	private String userName;
	
	public int getUserId() {
		return userId;
	}
	
	public void setUserId(int userId) {
		this.userId = userId;
	}
	
	public String getUserName() {
		return userName;
	}
	
	public void setUserName(String userName) {
		this.userName = userName;
	}
}

Step 2

package com.mugil.access;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.mugil.dto.UserDetails;

public class CreateUser {
	private static ServiceRegistry serviceRegistry;
	private static SessionFactory sessionFactory;
	
	public static void main(String[] args) {
		UserDetails objUserDetail =  new UserDetails();
		objUserDetail.setUserId(101);
		objUserDetail.setUserName("Mugil");
		
		SessionFactory sessionFact = createSessionFactory();
		Session session = sessionFact.openSession();
		session.beginTransaction();
		session.save(objUserDetail);
		session.getTransaction().commit();	
	}
	
	
	public static SessionFactory createSessionFactory() {
	    Configuration configuration = new Configuration();
	    configuration.configure();
	    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
	            configuration.getProperties()).build();
	    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	    return sessionFactory;
	}
}

In Some cases the hibernate.cfg.xml might become unrecognized.In such case the code should be changed to force the config to be picked from the file location.

public static SessionFactory createSessionFactory() 
{
  Configuration configuration = new Configuration().configure();	  
  configuration.configure("hibernate.cfg.xml");	  
  configuration.addAnnotatedClass(com.mugil.tutor.UserDetails.class);
	  
  serviceRegistry = new   StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
  sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  return sessionFactory;
}

Hibernate uses SessionFactory pattern internally as below

SessionFactory sessionFact = createSessionFactory();
Session session = sessionFact.openSession();
session.beginTransaction();
session.save(objUserDetail);
session.getTransaction().commit();	

1.Create Object for SessionFactory
2.Open Session to begin Transaction
3.Begin Transaction using beginTransaction() Method
4.Save the Object by Passing Object of the bean
5.Complete the Transaction using commit

Annotations
@Entity – Means entity as a whole>table would be created by the Name of the Entity
@Id – Tells the Primary Key

Having a Different table name from Class Name
Annotations

@Entity(name="User_Details")
public class Users 
{
 .
 .
}

Table with User_Details would be created instead of Users

Having a Different Column name from Object Name
Annotations

@Entity(name="User_Details")
public class Users 
{
 @Id
 @Column(name="USER_ID")
 private String UserId;
 .
 .
}

Columns with User_Id would be created instead of UserId

Appending String to Getters

public void setName(String name) 
{
  Name = name + " Append Test ";
}

Appending String to Getters

@Entity
@Table (name="User_Details")
public class Users 
{

}

The Entity Name Still remains the same but the table Name is different.

@Basic Annotation – Tells Hibernate to persist which it does by default

public class Users 
{
 @Basic
 private String UserName;
 . 
 .
}

@Basic has 2 Parameters – Fetch, optional. The only time you use @Basic is while applying the above options.

@Transient Annotation – Tells Hibernate to not store data in database

public class Users 
{
 @Transient
 private String UserName;
 . 
 .
}

@Temporal Annotation – Tells Hibernate to specify Date or Time

public class Users 
{
 @Temporal (TemporalType.Date)
 private String joinedDate;
 . 
 .
}

Without @Temporal the joinedDate is store along with TimeStamp in DB. Now using TemporalType(which is ENUM) you can select the type of data which can be stored in Database.

@Lob – Tells Hibernate to specify Date or Time

public class Users 
{
 @Lob
 private String Address;
 . 
 .
}

Tells the database field should be created as CLOB instead of VARCHAR(255).

modcount of the list lets you know if there has been a structural modification made that might cause the current operation to give incorrect results.

  List<String> arrNames = new ArrayList<String>();
  arrNames.add("Mugil");
  arrNames.add("Vinu");
  arrNames.add("Bala");
  arrNames.add("Madhu");		
  arrNames.remove(0);		
  arrNames.add("Swathi");		
  arrNames.remove(1);

When the control reaches
Line 6 The Size and Modcount of the arrNames would be 4
Line 7 The Size and Modcount would be 5 and size would be 3
Line 7 The Size and Modcount would be 6 and size would be 4

Fine the Screenshots below for further Details

Importing a Java Method in to JSP Page

package com.mugil.servlet;

public class Sample1 
{
  static int pincode = 600018;
  
  public String toString()
  {	
    return "600018";
  }
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import = "com.mugil.servlet.Sample1"%>    
 <body>
   <%=new Sample1()%>
 </body>

Note:
The following Code wont work

  <%=new Sample1();%>
  <% =new Sample1()%>

How to get Total Columns Returned by Query

 ResultSet rs = stmt.executeQuery(strSQL);
 ResultSetMetaData rsmd = rs.getMetaData();
 int columnsNumber = rsmd.getColumnCount();

How to get Column Name from Query

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 String name = rsmd.getColumnName(1);

How to get Column Count from Query and Loop Through That

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

// The column count starts from 1
for (int i = 1; i < columnCount + 1; i++ ) {
  String name = rsmd.getColumnName(i);
  // Do stuff with name
}

To Find a Column with particular Name

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 rs.getString(rs.findColumn("fullname"));

How to get List of Column Names from Query and Store it in a Array

 ResultSetMetaData meta = resultset.getMetaData();  
 Integer columncount = meta.getColumnCount();
 int count = 1 ; 
 String[] columnNames = null;

 while(columncount <=count)
  columnNames [i] = meta.getColumnName(i);

 System.out.println (columnNames.size());

How to Avoid unnessecary HTML Code while generating HTML for Mail or HTML File

Method1

DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName));

dosReport.wrtiteBytes("<table><thead>");

dosReport.writeBytes("<th>Column1</th>");
dosReport.writeBytes("<th>Column2</th>");
dosReport.writeBytes("<th>Column3</th>");
dosReport.writeBytes("<th>Column4</th>");
dosReport.writeBytes("<th>Column5</th>");
dosReport.writeBytes("<th>Column6</th>");
dosReport.writeBytes("<th>Column7</th>");
dosReport.writeBytes("<th>Column8</th>");
dosReport.writeBytes("<th>Column9</th>");

dosReport.wrtiteBytes("</thead>");

Method2
Replace with Below


DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName));
dosReport.wrtiteBytes("<table><thead>");

String[] columns = {"Column1", "Column2", "Column3", 
                    "Column4", "Column5", "Column6", 
                    "Column7", "Column8", "Column9"};

for(int i = 0; i < columns.length; i++)
 dosReport.writeBytes("<th>" + columns[i] +"</th>");

dosReport.wrtiteBytes("</thead>");

Disadvantage:
In the Method1 you have fine control over individual cell(tds) so you can add properties like align, individual stylings can be applied.

The below code reads a Sample.txt file and places the content in a newly created Html file Sample.html.

The file from which the content should be read is placed in a project directory which is printed in the console using the below java code.

System.out.println("Working Directory = " + System.getProperty("user.dir"));

The above code prints the current project directory in console.

package com.mugil.servlets;

import java.awt.Desktop;
import java.io.*;

class GenerateHTML 
{
    public static void main(String[] args) throws Exception 
    {    	
    	System.out.println("Working Directory = " +
                System.getProperty("user.dir"));
        BufferedReader br = new BufferedReader(new FileReader("Sample.txt"));
        File f = new File("source.htm");
        BufferedWriter bw = new BufferedWriter(new FileWriter(f));
        bw.write("<html>");
        bw.write("<body>");
        bw.write("<h1>ShowGeneratedHtml source</h1>");

        String line;
        while ((line=br.readLine())!=null) {
            bw.write(line);
            bw.newLine();
        }        
        bw.write("</body>");
        bw.write("</html>");

        br.close();
        bw.close();

        Desktop.getDesktop().browse(f.toURI());
    }
}

executeupdate vs executequery vs execute

ResultSet executeQuery() – Used for reading the content of the database.
output will be in form of ResultSet.
eg – SELECT statement.

int executeUpdate() – Used for DML(altering the database).
output will be in int.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

boolean execute() – Executing SQL statements.
output will be in boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

For setting the Bean value in struts-config.xml we should use the form-beans tag.The form-beans tag might contain any number of bean property defined within form-bean as below.

Defining a Simple Bean Property

<form-beans>
 <form-bean name="userBean" type="org.apache.struts.action.DynaActionForm">
   <form-property name="userName" initial="This is Bean Value" type="java.lang.String" />	
 </form-bean>
</form-beans>

In the above code I am creating a userBean and setting its value is initialized to This is Bean Value.

Now in the action mapping part of the struts-config.xml I am going to map the above created bean to path as said below

<action-mappings>
 <action path="/showBeanValue" type="org.apache.struts.actions.ForwardAction" parameter="/showBeanValue.jsp"/>				
 <action name="userBean" path="/Login" />		
</action-mappings>

In the first line I am defining action path as showBeanValue and it is going to forward to page showBeanValue.jsp when some one access the showBeanValue.do in url.

In the second statement I am creating a dummy form since the the html form action should not be empty.

 
  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
  <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>     
  <html:form action="/Login">
    <bean:write name="userBean" property="userName"></bean:write>
    <bean:write name="userBean" property="userAge"></bean:write>
  </html:form>