Wednesday, September 24, 2014

Java code : Batch Operation with Insert and Update Operation

Info
In this code during the batch operation  if the Insert operation get failed it will perform Update operation 

package com.raj.db;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


class Student{

private int id;
private String name;
private String queryType;

Student(){}

Student(int id, String name, String queryType){
this.id = id;
this.name = name;
this.queryType = queryType;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getQueryType() {
return queryType;
}

public void setQueryType(String queryType) {
this.queryType = queryType;
}
}

class DBManager{

private final String INSERT_QUERY = "INSERT INTO STUDENTS_DATA (ID, NAME) VALUES (?, ?)";
private final String UPDATE_QUERY = "UPDATE STUDENTS_DATA SET NAME = ?  WHERE ID = ?";

private Connection connection = null;

public void loadDriver(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("URL","DB_NAME","DB_PASSWORD");
} catch (Exception e) {
System.out.println("Error while executing preparedstatement, Reason: "+e.getMessage());
}
}

public void insertData(){
int response[] = null;
PreparedStatement prepStmt = null;
List<Student> studentList =  new ArrayList<Student>();

try{

connection.setAutoCommit(false);
prepStmt = connection.prepareStatement(INSERT_QUERY);

int starter = 7;
for(int i=starter; i<=starter+4; i++){
studentList.add(new Student(i,"student"+i, "INSERT"));
prepStmt.setInt(1, i);
prepStmt.setString(2, "Student"+i);
prepStmt.addBatch();
}
response = prepStmt.executeBatch();

} catch (BatchUpdateException be) {

try{
connection.rollback();
}catch(Exception ex){}

/*for(int command:be.getUpdateCounts()){
if(command == Statement.SUCCESS_NO_INFO){
System.out.println("SUCCESS "+command );
}else if(command == Statement.EXECUTE_FAILED){
System.out.println("FAILED "+command );
}
}*/
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Worker(studentList));
executor.shutdown();
System.out.println("Thread ShutDown");

}catch (Exception e) {
System.out.println("Error while executing batch, Reason: "+e.getMessage());
if(response!=null){
System.out.println("Response: "+response.length);
}

}finally{
closeQuietly(prepStmt);
closeQuietly(connection);
}
}

public void closeQuietly(Statement statement){
try {
            if (statement != null) {
            statement.close();
            }
        } catch (SQLException e) { }
}

public void closeQuietly(Connection connection){
try {
            if (connection != null) {
            connection.close();
            }
        } catch (SQLException e) { }
}


class Worker implements Runnable{


List<Student> dataList = null;
PreparedStatement insertPrepStmt = null;
PreparedStatement updatePrepStmt = null;
Worker(List<Student> data){
this.dataList = data;
}

@Override
public void run() {
loadDriver();
try{
insertPrepStmt = connection.prepareStatement(INSERT_QUERY);
updatePrepStmt = connection.prepareStatement(UPDATE_QUERY);

for(Student student: dataList){
String message = executeTask(student);
if(message.equalsIgnoreCase("INSERT_FAILED")){
System.out.println("INSERT FAILED");
student.setQueryType("UPDATE");
executeTask(student);
}
}

}catch(Exception ex){
System.out.println("Exception while executing preparedStatement, Reason: "+ex.getMessage());
}finally{
closeQuietly(insertPrepStmt);
closeQuietly(connection);
}
}


public String executeTask(Student data){
try{
if(data.getQueryType().equalsIgnoreCase("INSERT")){
System.out.println("INSERTING RECORD AGAING NOW");
insertPrepStmt.setInt(1, data.getId());
insertPrepStmt.setString(2,data.getName());
insertPrepStmt.execute();

}else if(data.getQueryType().equalsIgnoreCase("UPDATE")){
System.out.println("UPDATING NOW");
updatePrepStmt.setString(1,data.getName()+"-UPDATED");
updatePrepStmt.setString(2,data.getId()+"");
updatePrepStmt.executeUpdate();
}
connection.commit();
}catch(Exception ex){
return "INSERT_FAILED";
}
return "SUCCESS";
}
}
}

public class BatchOperationFlight {
public static void main(String bag[]){
System.out.println("--START--");
DBManager dbmanager = new DBManager();
dbmanager.loadDriver();
dbmanager.insertData();
System.out.println("--END--");
}
}

Keep Visiting :)

No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...