user2848031
user2848031

Reputation: 227

How to compare list of records against database in Java?

How to compare list of records against database? I have more than 1000 records in list and need to validate against database. How to validate each record from list to database? Select all the data from database and stored in list, then have to compare the values? Please advise...

The below code lists values to validate against database.

private void validatepart(HttpServletRequest req, Vector<String> errors) {
    Parts Bean = (Parts)req.getAttribute("partslist");
    Vector<PartInfo> List = Bean.getPartList();
    int sz = partList.size();
    for (int i = 0; i < sz; i++) {
        PartInfo part = (PartInfo)partList.elementAt(i);
        System.out.println(part.getNumber());
        System.out.println(part.getName());
    }
}

Upvotes: 1

Views: 2643

Answers (2)

Eric Hydrick
Eric Hydrick

Reputation: 3527

If your list of objects that you need to validate against the database includes a primary key, then you could just build a list of those primary key values and run a query like:

SELECT <PRIMARY KEY FIELD> FROM <TABLE> WHERE <PRIMARY_KEY_FIELD> IN <LIST OF PRIMARY KEYS> SORT BY <PRIMARY KEY FIELD> ASC;

Once you get that list back, you can compare the results. My instinct would be to put your data (and the query results too) into a Set object and then call removesAll() to get the items not in the database (reverse this for items in the database but not in your set):

yourDataSet.removeAll(queryResults);

This assumes that you have an equals() method implemented in your PartInfo object. You can see the Java API documentation for more details.

Upvotes: 0

crownjewel82
crownjewel82

Reputation: 437

This depends on what you mean by compare. If it's just one field then executing a query such as select * from parts_table where part_number = ?. It's not that much of a stretch to add more fields to that query. If nothing is returned you know it doesn't exist.

If you need to compare and know exactly which values are different then you can try something like this

List<String> compareObjects(PartInfo filePart, PartInfo dbPart) {
    List<String> different = new LinkedList<String>();

    if (!filePart.getNumber().equals(dbPart.getNumber())) {
        different.add("number");
    }
    //repeat for all your fields
    return different;
}

Upvotes: 1

Related Questions