All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.heliorm.sql.PojoCompare Maven / Gradle / Ivy

The newest version!
package com.heliorm.sql;

import com.heliorm.Field;
import com.heliorm.OrmException;
import com.heliorm.Table;
import com.heliorm.UncaughtOrmException;

import java.util.Optional;

/**
 * A comparable that compares two POJOs taking into account the metadata
 * available from a Table
 *
 * @author gideon
 */
final class PojoCompare implements Comparable> {

    private final PojoOperations pops;
    private final Table table;
    private final O pojo;

    public PojoCompare(PojoOperations pops, Table table, O pojo) {
        this.pops = pops;
        this.table = table;
        this.pojo = pojo;
    }

    public O getPojo() {
        return pojo;
    }

    @Override
    public int compareTo(PojoCompare w) {
        if (table.equals(w.table)) {
            Optional> primaryKey = table.getPrimaryKey();
            if (primaryKey.isPresent()) {
                try {
                    return pops.compareTo(pojo, w.getPojo(), primaryKey.get());
                } catch (OrmException ex) {
                    throw new UncaughtOrmException(ex.getMessage(), ex);
                }
            }
            if (pojo instanceof Comparable) {
                return ((Comparable)pojo).compareTo(w.getPojo());
            }
        }
        return table.getSqlTable().compareTo(w.table.getSqlTable());

    }

    @Override
    public int hashCode() {
        Optional> primaryKey = table.getPrimaryKey();
        if (primaryKey.isPresent()) {
            try {
                return pops.getValue(pojo, primaryKey.get()).hashCode();
            } catch (OrmException ex) {
                throw new UncaughtOrmException(ex.getMessage(), ex);
            }
        }
        return pojo.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (PojoCompare.class != obj.getClass()) {
            return false;
        }
        return compareTo((PojoCompare) obj) == 0;
    }

    int compareTo(PojoCompare w, Field field) throws UncaughtOrmException {
        try {
            return pops.compareTo(pojo, w.getPojo(), field);
        } catch (OrmException ex) {
            throw new UncaughtOrmException(ex.getMessage(), ex);
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy