Link to home
Start Free TrialLog in
Avatar of chaitu chaitu
chaitu chaituFlag for India

asked on

fetch the records from cache

say i have emp table

eno ename       sales
1    david      1100
2    lara       200
3    james    1000
1    david    1200
2    lara      5400
4    white    890
3    james    7500
1    david      1313

eno can be duplicate

when i give empno is 1

i want to display his sales i.e 1100,1200,1313

first time i will go to database and fetch the records

but next time onwards i dont go to database; i will fetch the records from cache;

i thought doing it using hashmap or hasptable ;both those two don't allow duplicate values(empno has duplicate values);

How to solve this problem.
Avatar of Mick Barry
Mick Barry
Flag of Australia image

you need to store a map of lists, keyed on empno
Avatar of chaitu chaitu

ASKER

sorry i didnt get u
your map would contains Lists (eg. Vectors) keyed on empno.
And each list would contain all employees with that empno
Avatar of tbone343
tbone343

Make a class called Employee something like:

class Employee {

private int id;
private String name;
private ArrayList sales;

blah blah
}

Then when you read the information, create objects of Employee, and you can store each one of these in a HashMap and key it on whatever you want.
"you can store each one of these in a HashMap and key it on whatever you want."

if i want give key on empno hashmap doesnt allow duplicates
chaituu,

 design a different key rather than (or Containing) eno, for example u can decide that the ID with Name is the real non repeatable combination in the table or what ever combination but their must be a unique combination in order to store ur table into Hashtable, in this case create class called EmpKey has member fields contains Id and Name and implements, equals() and hashCode() methods

if their is no unique combination then don't use Hashtable use a Collection or List based class like Vector to store ur Table Value Object or Data Transfer Object
You'll have no duplicates. Empno (eno) is the employee identifier. And those identifiers are unique.

Look, you could split your table on two databases (actually, it SHOULD be done this way):

employee table:
eno ename
1  david
2  lara
3  james
4  white

sales table:
eno sales
1  1100
1  1200
1  1313
2  200
2  5400
3  1000
3  7500
4  890

There should be defined the foreign key: sales.eno -> employee.eno.

Then you will be able to read the values from the database and create straight mapping: Hashtable<Integer, ArrayList<Integer>>

1 -> (1100, 1200, 1313)
2 -> (200, 5400)
3 -> (1000, 7500)
4 -> (890)
hi  RMaruszewski

all the fields in one table only there is no second table;

but in the emp data

if the empno is 1 then obviously his name should be same in ename field;
for empno 1 i cant give another name naa;

so i cant take eno and ename as key;
Try using EHCache. You can use this simple library for all your later caching efforts.
 - http://ehcache.sourceforge.net/
i want to do it using Collections package only
this is my Employee class

package example;
import java.util.*;
public class Employee
{

private int eno;
private String ename;
private java.util.ArrayList sales;

public void setENO(int eno)
{
     this.eno = eno;
}

public int getENO()
{
     return this.eno;
}
public void setEName(String ename)
{
     this.ename =ename;
}
public String getEName()
{
    return  this.ename ;
}
public void setSales(ArrayList sales)
{
     this.sales = sales;
}

public ArrayList getSales()
{
     return this.sales;
}
}

this is Cache class


package example;
import java.sql.*;
import java.io.*;
import example.Employee;
import java.util.*;

public class Cache
{
    public Cache()
    {
     try
        {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@172.16.31.12:1521:egl","scott","tiger");
        Statement stmt= con.createStatement();
        ResultSet rs=  stmt.executeQuery("SELECT ENO,ENAME,SALES FROM EMPTABLE");
        Employee employee = null;

        while(rs.next())
        {
            employee = new Employee();
            employee.setENO(rs.getInt(1));
            employee.setEName(rs.getString(2));

//*****How can I add sales to the particular empno in the Array List***************************///


        }

        }catch(ClassNotFoundException cnf)
        {
           cnf.printStackTrace();
        }
        catch(SQLException sql)
        {
            sql.printStackTrace();      
        }
    }

    public static void main(String[] args)
    {
        Cache cache = new Cache();
    }
}

in EMPTABLE eno can allow duplicates?
     ResultSet rs=  stmt.executeQuery("SELECT ENO,ENAME,SALES FROM EMPTABLE ORDER BY ENO");
      int lastEno = 0;
      int currentEno = 0;

      ArrayList employees = new ArrayList;
      ArrayList employeeSales = null;
      Employee employee = null;

       while(rs.next())
       {
          currentEno = rs.getInt(1);

          if (currentEno != lastEno)
          {
            if (employee != null)
            {
              employee.setESales(employeeSales);
              employees.add(employee);
            }

            employee = new Employee();
            employeeSales = new ArrayList();

            employee.setENO(currentEno);
            employee.setEName(rs.getString(2));

            lastEno = currentEno;
          }

          employeeSales.add(rs.getInt(3);
        }

        if (employee != null)
        {
          employee.setESales(employeeSales);
          employees.add(employee);
        }
on what key basis u add these sales ;

i can't add hashmap.put(eno,employee.getSales());
hashmap.put(new Integer(eno),employee.getSales()), or
hashmap.put(employeeName,employee.getSales())
as well i can write like this but i want to display which employee has his sales...

public class Cache
{
    public Cache()
    {
     try
        {
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@172.16.31.12:1521:egl","scott","tiger");
        Statement stmt= con.createStatement();
        ResultSet rs=  stmt.executeQuery("SELECT ENO,ENAME,SALES FROM EMPTABLE");
        int lastEno = 0;
      int currentEno = 0;

      ArrayList employees = new ArrayList();

ArrayList    employeeSales = new ArrayList();
      Employee employee = null;

       while(rs.next())
       {
     

            employee = new Employee();
     

            employee.setENO(rs.getInt(1));
            employee.setEName(rs.getString(2));
           employeeSales.add(new Integer(rs.getInt(3)));
             employee.setSales(employeeSales);

employees .add(employee);
         
         
         
        }

     

        }catch(ClassNotFoundException cnf)
        {
           cnf.printStackTrace();
        }
        catch(SQLException sql)
        {
            sql.printStackTrace();      
        }
    }

    public static void main(String[] args)
    {
        Cache cache = new Cache();
    }
}
Your solution won't work.
You don't reset the "employeeSales" list.
And the second employee will get the sales of the first employee.
And the third employee will get the sales of the first and second employee.
And so on...
You also create multiple instances of the "Employee" object for one employee. It's wrong solution.
Use my solution, then iterate through all the "employees", get "employee", display his identifier, name, and sales list.
Simple as that.
but as u said using this

 hashmap.put(new Integer(eno),employee.getSales()), or
hashmap.put(employeeName,employee.getSales())

hashmap doen't allow duplicates naaa.......
Look again at my solution. You have no duplicates there.
WHERE SHOULD I PUT THIS LINE

  hashmap.put(new Integer(currentEno),employee.getSales());
HashMap hashmap = new HashMap();
      ArrayList employees = new ArrayList();
      ArrayList employeeSales = null;
      Employee employee = null;

       while(rs.next())
       {
          currentEno = rs.getInt(1);

          if (currentEno != lastEno)
          {
            if (employee != null)
            {
              employee.setSales(employeeSales);
              employees.add(employee);
            }
            System.out.println("currentEno="+currentEno);
            employee = new Employee();
            employeeSales = new ArrayList();

            employee.setENO(currentEno);
            employee.setEName(rs.getString(2));
 System.out.println("ename="+rs.getString(2));
            lastEno = currentEno;
          }

          employeeSales.add(new Integer(rs.getInt(3)));
           if (employee != null)
            {
              employee.setSales(employeeSales);
              employees.add(employee);
            }
                hashmap.put(currentEno,employee.getSales());
         System.out.println("getSales="+employee.getSales());
        }  

here currentEno wil come as duplicates ;
ASKER CERTIFIED SOLUTION
Avatar of RMaruszewski
RMaruszewski

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
All of the solutions rely on the fact that the employee number will be returned from the SQL statement sorted by that number.  There is not guarantee that the database will return data in any order unless you include an "ORDER BY" clause in the query.

This is not necessary, just code the retrieval loop like this:
     HashMap employeesMap = new HashMap();
      ArrayList employeeSales = null;
      Employee employee = null;

      while(rs.next())
      {
          currentEno = new Integer(rs.getInt(1));
          employee=employeesMap.get(currentEno);
          if (currentEno==null) {
            employee.setENO(currentEno);
            employee.setEName(rs.getString(2));
          }
          employee.addSales(rs.getInt(3);
          employeesMap.put(currentEno, employee);
      }
...

When you create a new employee, also make sure you initialize the sales array.

The addSales(int sale) method just calls add() to the salesArray member variable.
If the employee has already been retrieved once, the employee# and Name will be the same, just add the new sales record to the array.