Monday, 8 August 2016

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.demo.hibernate.HibernateConnection;
import com.demo.pojo.User;

public class HibernateDAO<K extends Serializable, T extends Serializable> extends HibernateDaoSupport {

protected Class<T> domainClass = getDomainClass();

protected Class getDomainClass() {
        if (domainClass == null) {
            ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();

            // get T, so the 2nd class
            domainClass = (Class) thisType.getActualTypeArguments()[1];
        }
        System.out.println("Domain class is -> "+domainClass);
        return domainClass;
    }

public Object action(TaskManager taskManager){
try{
return taskManager.task();
}catch(Exception e){
e.printStackTrace();
return null;
}
}

public Collection<T> getAll(){
return (Collection<T>)action(new TaskManager() {
public Object task() throws Exception {
return getCachedHibernateTemplate().loadAll(domainClass);
}
});
}

private HibernateTemplate getCachedHibernateTemplate() {
    HibernateTemplate template = new HibernateTemplate();
    template.setSessionFactory(HibernateConnection.doHibernateConnection());
    template.setCacheQueries(true);
    return template;
    }

public interface TaskManager{
public Object task() throws Exception;
}
}

----------------------------------------------------------------------------

import org.springframework.orm.hibernate3.HibernateTemplate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public abstract class HibernateDAO<K extends Serializable, T extends Serializable> extends HibernateDaoSupport implements InitializingBean {
private Logger logger = LoggerFactory.getLogger(HibernateDAO.class);
public static final int MAX_RETRY = 5;

    protected Class<T> domainClass = getDomainClass();
   
public Object retryRun(RetriableTask task) {
Exception exception = null;
for (int i = 0; i < MAX_RETRY; i++) {
try {
return task.action();
} catch (Exception e) {
exception = e;
boolean deadlock = false;
for (StackTraceElement element: e.getStackTrace()) {
if (element.toString().toLowerCase().contains("deadlock")) {
deadlock = true;
}
}
if (e.getMessage() != null && deadlock) {
try {
Thread.sleep(8000);
} catch (Exception ex) {}
logger.warn("Deadlock detected. Retrying " + i + "/" + MAX_RETRY);
} else {
throw new RuntimeException(e);
}
}
}

throw new RuntimeException(exception);
}


    public T get(final K id) {
    return (T)retryRun(new RetriableTask() {

public Object action() throws Exception {
       return (T)getCachedHibernateTemplate().get(domainClass, id);
}
    });
    }

    public Collection<T> getAll() {
    return (Collection<T>)retryRun(new RetriableTask() {

public Object action() throws Exception {
           return getCachedHibernateTemplate().loadAll(domainClass);
}
    });
    }

    public K save(final T entity) {
    return (K)retryRun(new RetriableTask() {

public Object action() throws Exception {
           return (K)(getCachedHibernateTemplate().save(entity));
}
    });
    }

    public void saveOrUpdate(final T entity) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
       getCachedHibernateTemplate().saveOrUpdate(entity);
       getCachedHibernateTemplate().flush();
       return null;
}
    });
    }

    public void update(final T entity) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
           getCachedHibernateTemplate().update(entity);
           getCachedHibernateTemplate().flush();
       return null;
}
    });
    }

    public void delete(final T entity) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
           getCachedHibernateTemplate().delete(entity);
       return null;
}
    });
    }
   
    public void saveOrUpdateAll(final Collection<T> list) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
    getCachedHibernateTemplate().saveOrUpdateAll(list);
    getCachedHibernateTemplate().flush();
       return null;
}
    });
    }

    public void deleteById(final K id) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
       T obj = get(id);
       getCachedHibernateTemplate().delete(obj);
       getCachedHibernateTemplate().flush();
       return null;
}
    });
    }
   
    protected HibernateTemplate getCachedHibernateTemplate() {
    HibernateTemplate template = getHibernateTemplate();
    template.setCacheQueries(true);
    return template;
    }

    protected Class getDomainClass() {
        if (domainClass == null) {
            ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();

            // get T, so the 2nd class
            domainClass = (Class) thisType.getActualTypeArguments()[1];
        }
        return domainClass;
    }

    public List find(final String query) {
    return (List)retryRun(new RetriableTask() {
public Object action() throws Exception {
    return getCachedHibernateTemplate().find(query);      
}
    });
    }

    public List find(final String query, final Object[] params) {
    return (List)retryRun(new RetriableTask() {
public Object action() throws Exception {
    return getCachedHibernateTemplate().find(query, params);
}
    });
    }

    public T findSingle(final String query, final Object[] params) {
    return (T)retryRun(new RetriableTask() {
public Object action() throws Exception {
    List<T> list = getCachedHibernateTemplate().find(query, params);
    if (list.isEmpty()) {
    return null;
    }
   
    return list.get(0);
}
    });
    }

    public void bulkUpdate(final String query, final Object[] params) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
    getCachedHibernateTemplate().bulkUpdate(query, params);
    getCachedHibernateTemplate().flush();
    return null;
}
    });
    }

    public void bulkUpdate(final String query) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
    getCachedHibernateTemplate().bulkUpdate(query);
    getCachedHibernateTemplate().flush();
    return null;
}
    });
    }

    public void saveAll(final Collection<T> entities) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
    _saveAll(entities);
    return null;
}
    });
    }

    private void _saveAll(final Collection<T> entities) {
    getHibernateTemplate().execute(new HibernateCallback() {

public Object doInHibernate(Session session)
throws HibernateException, SQLException {
try {
// consider packets of 1000 max
int counter = 0;
session.beginTransaction();
for (T entity: entities) {
session.save(entity);
}
session.getTransaction().commit();
session.flush();
session.clear();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
}
return null;
}
   
    });
    }

    public boolean updateAll(final Collection<T> entities) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
return _updateAll(entities);
   
}
    });    
    return true;
    }

    private boolean _updateAll(final Collection<T> entities) {
    getHibernateTemplate().execute(new HibernateCallback() {

public Object doInHibernate(Session session)
throws HibernateException, SQLException {
try {
session.beginTransaction();
for (T entity: entities) {
session.update(entity);
}
session.getTransaction().commit();
session.flush();
session.clear();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
return false;
}
return true;
}
   
    });
return true;
    }

    public void deleteAll(final Collection<T> entities) {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
_deleteAll(entities);
    return null;
}
    });    
    }

    private void _deleteAll(final Collection<T> entities) {
    getHibernateTemplate().execute(new HibernateCallback() {

public Object doInHibernate(Session session)
throws HibernateException, SQLException {
try {
session.beginTransaction();
for (T entity: entities) {
session.delete(entity);
}
session.getTransaction().commit();
session.flush();
session.clear();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
}
return null;
}
   
    });
    }

    public void flush() {
    retryRun(new RetriableTask() {
public Object action() throws Exception {
    getCachedHibernateTemplate().flush();
    return null;
}
    });    
    }
   
    public interface RetriableTask {
    public Object action() throws Exception;
    }
}

Monday, 1 August 2016

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

import com.demo.pojo.Products;
import com.demo.pojo.User;

public class HibernateConnection {

public static SessionFactory sessionFactory;

public static SessionFactory doHibernateConnection(){
Properties database = new Properties();
database.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
database.setProperty("hibernate.connection.username", "root");
database.setProperty("hibernate.connection.password", "");
database.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/spring");
database.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

Configuration cfg = new Configuration()
.setProperties(database)
.addPackage("com.demo.pojo")
.addAnnotatedClass(User.class)
.addAnnotatedClass(Products.class);

StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());

sessionFactory = cfg.buildSessionFactory(ssrb.build());

return sessionFactory;

}

}

--------------------------------------------------

<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>HibernateStuff</groupId>
<artifactId>HibernateStuff</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Hibernate Stuff</name>
<description>Hibernate Stuff</description>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.5.4-Final</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
</dependencies>
</project>

Saturday, 25 October 2014

Java beans

Java bean is reusable software component for java. We can access them using getter and setter methods.

It has default or no argument constructor. We can create a bean for a class in xml file and then use their members in java code.

See in Java spring framework we will create beans with spring inbuilt classes.

Now a days it is a good idea to create an object of a class using Java bean.

We will create Java beans in xml file.

Thursday, 23 October 2014

Eclipse and Maven configuration.

Download Java and install it in your computer.

As you know you can even write your java code with command line and a txt editor but its not a good idea to develop a software. So there are some good Integrated Development Environments (IDEs) like :-

1) Eclipse

2) Netbeans

I prefer eclipse but it depends on you. Both are good and user friendly and both are open source and will be.

So download eclipse from above link.

What is Apache Maven ?

It is a build automation tool mainly used for Java projects. As we know that sometimes we need to use 3rd party jars. So we go to google.com and download that .jar file and then add that .jar file to our Java project.

But now a days this is not a good idea to deal with .jar files. So Apache Maven is used. When you create maven project in eclipse it generates pom.xml file for your maven project. So you just add dependency for that .jar file with version info and maven will download and add to your class path automatically.

Why Apache Maven ?

As you have seen how jar files can be used easily with maven then who thinks to download manually rather than automatically. As Maven downloads jar files automatically so more and more developers love to use it rather then tradition way. Also it is easy to use maven in eclipse using m2e eclipse plugin that you can get from eclipse market place.

Introduction to Java Spring Framework.

Spring framework is very famous open source framework based on Java. Now a days more and more web apps are made of Spring Framework because of its good features.

The first version was written by Rod Johnson and it was first released under Apache license.

There are some good modules of Spring Framework as described below :-

Spring Core Container: This is the base module of Spring and provides spring containers (BeanFactory and ApplicationContext).

Aspect Oriented Programming: Enables implementation of cross-cutting concerns.

Data Access: To work ORM (Object Relational Mapping) like Hibernate.

MVC: Model-View-Controller structure to easily manage your complex systems.

Inversion Of Control: It is to be done via Dependency Injection.

Why use Java Spring Framework ?

So you have seen modules as described above and you know that MVC structure is very famous now a days and Java and Spring Framework both are open source and other modules add advantage to this framework so now a days more and more Enterprise Applications made in Java Spring Framework. More and more developers use Spring Framework.

All know that Java is strong , secure and robust programming language and spring framework is easy to use so people love to use Java Spring Framework.