<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.natvesql</groupId>
<artifactId>NativeSQL_Maven</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<artifactId>hibernate-core</artifactId>
<groupId>org.hibernate</groupId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- EHCache uses slf4j for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n
# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\\hibernate-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!-- <property name="dialect"> org.hibernate.dialect.Oracle10gDialect </property>
<property name="connection.url"> jdbc:oracle:thin:@localhost:1521:XE </property>
<property name="connection.username">kcv</property> <property name="connection.password">kcv</property>
<property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver
</property> <property name="myeclipse.connection.profile"> oracle.jdbc.driver.OracleDriver
</property> <property name="connection.autocommit">true</property> -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="show_sql">true</property>
<property name="connection.autocommit">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="format_sql">true</property>
<mapping resource="EmployeeBean.hbm.xml" />
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.cv.hibernate.nativesql.model">
<class name="EmployeeBean" table="EmployeeBean_Native_SQL">
<id name="id" type="long">
<column name="EID" precision="10" scale="0" />
<!-- <generator class="assigned" /> -->
</id>
<property name="firstName" type="string">
<column name="FIRSTNAME" length="29" />
</property>
<property name="lastName" type="string">
<column name="LASTNAME" length="29" />
</property>
<property name="email" type="string">
<column name="EMAIL" length="39" />
</property>
</class>
<sql-query name="emp_fun_select3" callable="true">
<return-scalar column="cnt" type="int" />
<![CDATA[CALL emp_fun_select3(?,?,?)]]>
</sql-query>
<!-- <sql-query name="selectByEmail"> <return-scalar column="eid" type="int"
/> <return-scalar column="firstname" type="string" /> <![CDATA[ select eid,firstName
from EmployeeBean_Native_SQL where email like :p1]]> </sql-query> <sql-query
name="get_emp_fname_lname_pro_mysql"> <return-scalar column="firstname" type="string"
/> <return-scalar column="lastname" type="string" /> <![CDATA[CALL get_emp_fname_lname_pro_mysql(?)]]>
</sql-query> <sql-query name="deleteByMaxId"> <![CDATA[ delete from EmployeeBean_Native_SQL
where eid=(select max(eid) from EmployeeBean_Native_SQL)]]> </sql-query>
<sql-query name="NativeSQLDeleteFunctionByEmail" callable="true"> {?=call
emp_del(?)} </sql-query> <sql-query name="NativeSQLDeleteFunctionByEmail"
callable="true"> <return-scalar column="cnt" type="int" /> {?=call emp_del_postgres3(?)}
</sql-query> <sql-query name="test9" callable="true"> <return-scalar column="firstname"
type="string" /> <return-scalar column="lastname" type="string" /> {call
emp_pro9(?,:p1)} </sql-query> <sql-query name="test2" callable="true"> <return
class="EmployeeBean" /> {?=call emp_fun(?)} </sql-query> <sql-query name="test3"
callable="true"> {?=call emp_del(?)} </sql-query> <sql-query name="test4"
callable="true"> <return-scalar column="cnt" type="int" /> {call emp_pro(?,?,?)}
</sql-query> <sql-query name="test5" callable="true"> <return class="Emp"
/> {call emp_pro3(?,?)} </sql-query> <sql-query name="test6" callable="true">
{call emp_pro4(?,:p1)} </sql-query> -->
</hibernate-mapping>
package com.cv.hibernate.nativesql.util;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.cv.hibernate.nativesql.model.EmployeeBean;
/**
* @author Chandra Vardhan
*/
/**
* Configures and provides access to Hibernate sessions, tied to the current
* thread of execution. Follows the Thread Local Session pattern, see
* {@link http://hibernate.org/42.html }.
*/
public class HibernateUtil {
private final static Logger logger = Logger.getLogger(HibernateUtil.class);
/**
* Location of hibernate.cfg.xml file. Location should be on the classpath
* as Hibernate uses #resourceAsStream style lookup for its configuration
* file. The default classpath location of the hibernate config file is in
* the default package. Use #setConfigFile() to update the location of the
* configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory;
static {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtil() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
System.exit(0);
}
}
/**
* return session factory
*
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
public static void saveOrUpdate() {
Session session = getSession();
for (int i = 100; i <= 105; i++) {
EmployeeBean eb = new EmployeeBean();
eb.setId(new Long(i));
eb.setFirstName("chandra");
eb.setLastName("vardhan");
eb.setEmail("meetkodam@gmail.com");
session.beginTransaction();
session.saveOrUpdate(eb);
session.getTransaction().commit();
}
logger.info("Saved successful...");
session.close();
}
}
package com.cv.hibernate.nativesql.model;
public class MyBean {
private long result;
public long getResult() {
return result;
}
public void setResult(long result) {
this.result = result;
}
}
package com.cv.hibernate.nativesql.model;
/**
* @author Chandra Vardhan
*/
public class EmployeeBean {
private long id;
private String firstName;
private String lastName;
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.cv.hibernate.nativesql;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.nativesql.util.HibernateUtil;
public class NativeSQLSelectByEmail {
/**
* @param args
*/
private final static Logger logger = Logger
.getLogger(NativeSQLSelectByEmail.class);
public static void main(String[] args) {
// Am creating the records by this statement.
HibernateUtil.saveOrUpdate();
Session session = HibernateUtil.getSession();
Query q1 = session.getNamedQuery("selectByEmail");
q1.setString("p1", "%gmail.com");
q1.setFirstResult(1);
q1.setMaxResults(2);// pagination concept working here....
List list = q1.list();
if (list != null && !list.isEmpty()) {
logger.info("Return type of the class is : "
+ list.get(0).getClass());
for (int i = 0; i < list.size(); ++i) {
Object[] row = (Object[]) list.get(i);
String result = null;
for (int k = 0; k < row.length; k++) {
if (result == null) {
result = row[k].toString() + " ";
} else {
result += row[k].toString() + " ";
}
}
logger.info(result);
}
} else {
logger.info("No Records found for the specified input...");
}
}
}
package com.cv.hibernate.nativesql;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.nativesql.model.EmployeeBean;
import com.cv.hibernate.nativesql.util.HibernateUtil;
public class NativeSQLSelectByEid {
/**
* @param args
*/
private final static Logger logger = Logger
.getLogger(NativeSQLSelectByEid.class);
public static void main(String[] args) {
// Am creating the records by this statement.
HibernateUtil.saveOrUpdate();
Session session = HibernateUtil.getSession();
Query query = session.getNamedQuery("selectByEid");
query.setInteger("p1", 100);
query.setInteger("p2", 105);
List list = query.list();
if (list != null && !list.isEmpty()) {
logger.info("return type of the class : " + list.get(0).getClass());
for (int i = 0; i < list.size(); ++i) {
EmployeeBean eb = (EmployeeBean) list.get(i);
logger.info(eb.getId() + " " + eb.getFirstName() + " "
+ eb.getLastName() + " " + eb.getEmail());
}
} else {
logger.info("No Records found for the specified input...");
}
}
}
package com.cv.hibernate.nativesql;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.nativesql.util.HibernateUtil;
public class NativeSQLDeleteByID {
/**
* @param args
*/
private final static Logger logger = Logger.getLogger(NativeSQLDeleteByID.class);
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
Query q1 = session.getNamedQuery("deleteByMaxId");
int res = q1.executeUpdate();
logger.info("Return type of the class is : " + res);
}
}
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.natvesql</groupId>
<artifactId>NativeSQL_Maven</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<artifactId>hibernate-core</artifactId>
<groupId>org.hibernate</groupId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- EHCache uses slf4j for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n
# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\\hibernate-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!-- <property name="dialect"> org.hibernate.dialect.Oracle10gDialect </property>
<property name="connection.url"> jdbc:oracle:thin:@localhost:1521:XE </property>
<property name="connection.username">kcv</property> <property name="connection.password">kcv</property>
<property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver
</property> <property name="myeclipse.connection.profile"> oracle.jdbc.driver.OracleDriver
</property> <property name="connection.autocommit">true</property> -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.timeout">5000</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="show_sql">true</property>
<property name="connection.autocommit">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="format_sql">true</property>
<mapping resource="EmployeeBean.hbm.xml" />
</session-factory>
</hibernate-configuration>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.cv.hibernate.nativesql.model">
<class name="EmployeeBean" table="EmployeeBean_Native_SQL">
<id name="id" type="long">
<column name="EID" precision="10" scale="0" />
<!-- <generator class="assigned" /> -->
</id>
<property name="firstName" type="string">
<column name="FIRSTNAME" length="29" />
</property>
<property name="lastName" type="string">
<column name="LASTNAME" length="29" />
</property>
<property name="email" type="string">
<column name="EMAIL" length="39" />
</property>
</class>
<sql-query name="emp_fun_select3" callable="true">
<return-scalar column="cnt" type="int" />
<![CDATA[CALL emp_fun_select3(?,?,?)]]>
</sql-query>
<!-- <sql-query name="selectByEmail"> <return-scalar column="eid" type="int"
/> <return-scalar column="firstname" type="string" /> <![CDATA[ select eid,firstName
from EmployeeBean_Native_SQL where email like :p1]]> </sql-query> <sql-query
name="get_emp_fname_lname_pro_mysql"> <return-scalar column="firstname" type="string"
/> <return-scalar column="lastname" type="string" /> <![CDATA[CALL get_emp_fname_lname_pro_mysql(?)]]>
</sql-query> <sql-query name="deleteByMaxId"> <![CDATA[ delete from EmployeeBean_Native_SQL
where eid=(select max(eid) from EmployeeBean_Native_SQL)]]> </sql-query>
<sql-query name="NativeSQLDeleteFunctionByEmail" callable="true"> {?=call
emp_del(?)} </sql-query> <sql-query name="NativeSQLDeleteFunctionByEmail"
callable="true"> <return-scalar column="cnt" type="int" /> {?=call emp_del_postgres3(?)}
</sql-query> <sql-query name="test9" callable="true"> <return-scalar column="firstname"
type="string" /> <return-scalar column="lastname" type="string" /> {call
emp_pro9(?,:p1)} </sql-query> <sql-query name="test2" callable="true"> <return
class="EmployeeBean" /> {?=call emp_fun(?)} </sql-query> <sql-query name="test3"
callable="true"> {?=call emp_del(?)} </sql-query> <sql-query name="test4"
callable="true"> <return-scalar column="cnt" type="int" /> {call emp_pro(?,?,?)}
</sql-query> <sql-query name="test5" callable="true"> <return class="Emp"
/> {call emp_pro3(?,?)} </sql-query> <sql-query name="test6" callable="true">
{call emp_pro4(?,:p1)} </sql-query> -->
</hibernate-mapping>
package com.cv.hibernate.nativesql.util;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.cv.hibernate.nativesql.model.EmployeeBean;
/**
* @author Chandra Vardhan
*/
/**
* Configures and provides access to Hibernate sessions, tied to the current
* thread of execution. Follows the Thread Local Session pattern, see
* {@link http://hibernate.org/42.html }.
*/
public class HibernateUtil {
private final static Logger logger = Logger.getLogger(HibernateUtil.class);
/**
* Location of hibernate.cfg.xml file. Location should be on the classpath
* as Hibernate uses #resourceAsStream style lookup for its configuration
* file. The default classpath location of the hibernate config file is in
* the default package. Use #setConfigFile() to update the location of the
* configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory;
static {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtil() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
System.exit(0);
}
}
/**
* return session factory
*
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
public static void saveOrUpdate() {
Session session = getSession();
for (int i = 100; i <= 105; i++) {
EmployeeBean eb = new EmployeeBean();
eb.setId(new Long(i));
eb.setFirstName("chandra");
eb.setLastName("vardhan");
eb.setEmail("meetkodam@gmail.com");
session.beginTransaction();
session.saveOrUpdate(eb);
session.getTransaction().commit();
}
logger.info("Saved successful...");
session.close();
}
}
package com.cv.hibernate.nativesql.model;
public class MyBean {
private long result;
public long getResult() {
return result;
}
public void setResult(long result) {
this.result = result;
}
}
package com.cv.hibernate.nativesql.model;
/**
* @author Chandra Vardhan
*/
public class EmployeeBean {
private long id;
private String firstName;
private String lastName;
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.cv.hibernate.nativesql;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.nativesql.util.HibernateUtil;
public class NativeSQLSelectByEmail {
/**
* @param args
*/
private final static Logger logger = Logger
.getLogger(NativeSQLSelectByEmail.class);
public static void main(String[] args) {
// Am creating the records by this statement.
HibernateUtil.saveOrUpdate();
Session session = HibernateUtil.getSession();
Query q1 = session.getNamedQuery("selectByEmail");
q1.setString("p1", "%gmail.com");
q1.setFirstResult(1);
q1.setMaxResults(2);// pagination concept working here....
List list = q1.list();
if (list != null && !list.isEmpty()) {
logger.info("Return type of the class is : "
+ list.get(0).getClass());
for (int i = 0; i < list.size(); ++i) {
Object[] row = (Object[]) list.get(i);
String result = null;
for (int k = 0; k < row.length; k++) {
if (result == null) {
result = row[k].toString() + " ";
} else {
result += row[k].toString() + " ";
}
}
logger.info(result);
}
} else {
logger.info("No Records found for the specified input...");
}
}
}
package com.cv.hibernate.nativesql;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.nativesql.model.EmployeeBean;
import com.cv.hibernate.nativesql.util.HibernateUtil;
public class NativeSQLSelectByEid {
/**
* @param args
*/
private final static Logger logger = Logger
.getLogger(NativeSQLSelectByEid.class);
public static void main(String[] args) {
// Am creating the records by this statement.
HibernateUtil.saveOrUpdate();
Session session = HibernateUtil.getSession();
Query query = session.getNamedQuery("selectByEid");
query.setInteger("p1", 100);
query.setInteger("p2", 105);
List list = query.list();
if (list != null && !list.isEmpty()) {
logger.info("return type of the class : " + list.get(0).getClass());
for (int i = 0; i < list.size(); ++i) {
EmployeeBean eb = (EmployeeBean) list.get(i);
logger.info(eb.getId() + " " + eb.getFirstName() + " "
+ eb.getLastName() + " " + eb.getEmail());
}
} else {
logger.info("No Records found for the specified input...");
}
}
}
package com.cv.hibernate.nativesql;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.nativesql.util.HibernateUtil;
public class NativeSQLDeleteByID {
/**
* @param args
*/
private final static Logger logger = Logger.getLogger(NativeSQLDeleteByID.class);
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
Query q1 = session.getNamedQuery("deleteByMaxId");
int res = q1.executeUpdate();
logger.info("Return type of the class is : " + res);
}
}
No comments:
Post a Comment