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

com.harium.database.module.OrmLiteDatabaseModule Maven / Gradle / Ivy

There is a newer version: 1.1.3
Show newest version
package com.harium.database.module;

import com.harium.database.model.BaseDAO;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class OrmLiteDatabaseModule implements DatabaseModule {

    protected ConnectionSource connectionSource;

    protected List> registers = new ArrayList>();
    protected Map, BaseDAO> daos = new HashMap, BaseDAO>();

    public void init() {
        init(false);
    }

    public void init(boolean clearDatabase) {
        try {
            connectionSource = initConnection();
            createDAOs();

            if (clearDatabase) {
                clear();
            }
            setupDatabase(connectionSource);

            initDAOs(connectionSource);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected abstract ConnectionSource initConnection() throws SQLException;

    public void clear() throws Exception {
        for (BaseDAO dao : registers) {
            TableUtils.dropTable(connectionSource, dao.getKlass(), true);
        }
    }

    private void setupDatabase(ConnectionSource connectionSource) throws SQLException {
        for (BaseDAO dao : registers) {
            TableUtils.createTableIfNotExists(connectionSource, dao.getKlass());
        }
    }

    private void createDAOs() {
        for (BaseDAO register : registers) {
            addDAO(register);
        }
    }

    private void initDAOs(ConnectionSource connectionSource) {
        for (BaseDAO dao : registers) {
            dao.init(connectionSource);
        }
    }

    private BaseDAO addDAO(BaseDAO baseDAO) {
        daos.put(baseDAO.getKlass(), baseDAO);
        return baseDAO;
    }

    public BaseDAO getDAO(Class klass) {
        return daos.get(klass);
    }

    public void register(BaseDAO dao) {
        registers.add(dao);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy