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

com.mycomm.dao.dao4comm.orm.impl.MyOrmSession Maven / Gradle / Ivy

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycomm.dao.dao4comm.orm.impl;

import com.mycomm.IProtocol.sql.annotation.MyTable;
import com.mycomm.dao.dao4comm.ResultHelp;
import com.mycomm.dao.dao4comm.annotation.dialect.DialectConfiguration;
import com.mycomm.dao.dao4comm.annotation.dialect.DialectHandlerSelector;
import com.mycomm.dao.dao4comm.annotation.dialect.FieldMetaData;
import com.mycomm.dao.dao4comm.annotation.dialect.SqlBuilder;
import com.mycomm.dao.dao4comm.framework.AnnotationStructureStrategy;
import com.mycomm.dao.dao4comm.framework.OrmObjectLoader;
import com.mycomm.dao.dao4comm.framework.impl.OneToManyOnlyOrmObjectLoader;
import com.mycomm.dao.dao4comm.framework.impl.OneToOneOnlyOrmObjectLoader;
import com.mycomm.dao.dao4comm.framework.impl.SimpleOrmObjectLoader;
import com.mycomm.dao.dao4comm.orm.MySession;
import com.mycomm.dao.dao4comm.orm.OrmBaseSupport;
import com.mycomm.dao.dao4comm.util.AnnotationParser;
import com.mycomm.dao.dao4comm.util.ClassAnalysis;
import com.mycomm.dao.dao4comm.util.ConstantsKeeper;
import com.mycomm.dao.dao4comm.util.MyQueryCondition;
import com.mycomm.dao.dao4comm.util.PreparedStatementBuilder;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

/**
 *
 * @author jw362j
 */
//@Repository
public class MyOrmSession extends OrmBaseSupport implements MySession {

    public long getCount(Class clz) {
        if (clz == null) {
            log.info("entityClass is null!");
            return 0l;
        }
        checkTableExist(clz);
        String tableName = AnnotationParser.LoadAnnotationStructureStrategy(clz).getTableName();
        String idColumName = AnnotationParser.LoadAnnotationStructureStrategy(clz).getIdColumName();
        Field[] fields = clz.getDeclaredFields();
        if (fields == null || fields.length <= 0) {
            log.info("myTable DeclaredFields Annotation is null!");
            return 0l;
        }
        //got tablename and primary key,build the sql :select count(theid) from theTableName
        String getCountSql = "select count(" + idColumName + ") from " + tableName;
        return getJdbcTemplate().queryForObject(getCountSql, Long.class);
    }

    public int[] saveList(Object[] objects) {
        if (objects == null || objects.length <= 0) {
            return null;
        }
        //clean the data ,remove the useless data
        List targets = new ArrayList();
        for (Object o : objects) {
            if (o != null) {
                targets.add(o);
            }
        }
        objects = targets.toArray();
        checkTableExist(objects[0].getClass());
        Field[] fields = objects[0].getClass().getDeclaredFields();
        SqlBuilder tableCreator = DialectHandlerSelector.selectTableCreator(DialectConfiguration.dbType);
        String tableName = AnnotationParser.LoadAnnotationStructureStrategy(objects[0].getClass()).getTableName();
//        String tableName = AnnotationParser.getTableName(objects[0].getClass());
        final String sqlInsert = tableCreator.doInsertInToTable(tableName, fields);
        final Map metas[] = new Map[objects.length];
        int fieldIndex = 0;
        for (Object entity : objects) {
//            Field[] myfields = entity.getClass().getDeclaredFields();
            metas[fieldIndex++] = ClassAnalysis.buildFieldsMap(fields, entity);
        }
        int[] updateCounts = getJdbcTemplate().batchUpdate(
                sqlInsert,
                new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                PreparedStatementBuilder.initPreparedStatement(metas[i], ps);
            }

            @Override
            public int getBatchSize() {
                return metas.length;
            }
        }
        );
        return updateCounts;
    }

    public long save(Object object) {
        if (object == null) {
            return -1l;
        }
        checkTableExist(object.getClass());
        Field[] fields = object.getClass().getDeclaredFields();
        SqlBuilder tableCreator = DialectHandlerSelector.selectTableCreator(DialectConfiguration.dbType);
        String tableName = AnnotationParser.LoadAnnotationStructureStrategy(object.getClass()).getTableName();
        final String sqlInsert = tableCreator.doInsertInToTable(tableName, fields);
        final Map metas = ClassAnalysis.buildFieldsMap(fields, object, false);
        KeyHolder holder = new GeneratedKeyHolder();
        getJdbcTemplate().update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement ps = con.prepareStatement(sqlInsert, PreparedStatement.RETURN_GENERATED_KEYS);
                PreparedStatementBuilder.initPreparedStatement(metas, ps);
                return ps;
            }
        }, holder);
        return holder.getKey().longValue();
    }

    public void delete(Class clz, long theId) {
        deleteList(clz, new long[]{theId});
        if (myTableCacheService != null) {
            myTableCacheService.removeObject(clz, theId);
        }
    }

    public void deleteList(Class clz, long[] theIds) {
        // delete from MyClass where id=1;
        if (theIds == null || theIds.length <= 0 || clz == null) {
            return;
        }
//        String idName = AnnotationParser.getTableIdColumName(clz);
        String idName = AnnotationParser.LoadAnnotationStructureStrategy(clz).getIdColumName();
        StringBuilder sql_delete = new StringBuilder();
        sql_delete.append("delete from ").append(AnnotationParser.LoadAnnotationStructureStrategy(clz).getTableName()).append(" where ").append(idName).append(" in(");
        for (long myid : theIds) {
            sql_delete.append(myid).append(" ,");
            if (myTableCacheService != null) {
                myTableCacheService.removeObject(clz, myid);
            }
        }
        sql_delete.deleteCharAt(sql_delete.length() - 1);
        sql_delete.append(")");
        log.info("the sql is :" + sql_delete);
        getJdbcTemplate().execute(sql_delete.toString());
    }

    public Object find(Class clz, long theid, boolean forceReload) {
        if (!forceReload) {
            if (myTableCacheService != null) {
                Object object = myTableCacheService.get(clz, theid);
                if (object != null) {
                    return object;
                }
            }
        }

        String idColumName = AnnotationParser.LoadAnnotationStructureStrategy(clz).getIdColumName();
        ResultHelp ss = find(clz, new MyQueryCondition(0, 1, null, idColumName + " = ? ", new Object[]{theid}, new int[]{java.sql.Types.BIGINT}, null));
        if (ss == null) {
            return null;
        }
        List list = ss.getResultlist();
        if (list == null || list.size() <= 0) {
            return null;
        }
        if (myTableCacheService != null) {
            myTableCacheService.put(clz, list.get(0), theid);
        }
        return list.get(0);
    }

    public Object find(Class clz, long theid) {
        return find(clz, theid, false);
    }

    public ResultHelp find(Class clz, MyQueryCondition condition) {
        if (clz == null) {
            return null;
        }
        if (condition == null) {
            return getScrollData(clz, -1, -1, null, null, null, null, null);
        }
        return getScrollData(clz, condition.getFirstindex(), condition.getMaxresult(), condition.getColums(), condition.getWheresql(), condition.getQueryParamsNames(), condition.getQueryParamsTypes(), condition.getOrderby());

    }

    public int update(Object obj) {
        if (obj == null) {
            return -1;
        }
        int[] rs = updates(new Object[]{obj});
        if (myTableCacheService != null) {
            long id_flag = AnnotationParser.getIdValue(obj);
            if (id_flag > 0) {
                myTableCacheService.put(obj.getClass(), obj, id_flag);
            }
        }

        return rs == null ? -1 : rs[0];
    }

    public int[] updates(Object[] entities) {
        if (entities == null || entities.length <= 0) {
            log.info("the entityClass is null or entity is null in save!");
            return null;
        }
        List targets = new ArrayList();
        for (Object o : entities) {
            if (o != null) {
                targets.add(o);
                if (myTableCacheService != null) {
                    long id_flag = AnnotationParser.getIdValue(o);
                    if (id_flag > 0) {
                        myTableCacheService.put(o.getClass(), o, id_flag);
                    }
                }

            }
        }
        entities = targets.toArray();
        String tableName = AnnotationParser.LoadAnnotationStructureStrategy(entities[0].getClass()).getTableName();
        String idColumName = AnnotationParser.LoadAnnotationStructureStrategy(entities[0].getClass()).getIdColumName();
        Field[] fields = entities[0].getClass().getDeclaredFields();
        SqlBuilder tableCreator = DialectHandlerSelector.selectTableCreator(DialectConfiguration.dbType);
        final String sql_update = tableCreator.doUpdateTable(tableName, fields, idColumName);
        final Map metas[] = new Map[entities.length];
        int fieldIndex = 0;
        for (Object entity : entities) {
//            Field[] myfields = entity.getClass().getDeclaredFields();
            metas[fieldIndex++] = ClassAnalysis.buildFieldsMap(fields, entity, true);
        }
        int[] updateCounts = getJdbcTemplate().batchUpdate(
                sql_update,
                new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                PreparedStatementBuilder.initPreparedStatement(metas[i], ps);
            }

            @Override
            public int getBatchSize() {
                return metas.length;
            }
        }
        );
        return updateCounts;
    }

    public int halfUpdate(Object obj, String colums[]) {
        int[] updates = halfUpdates(new Object[]{obj}, colums);
        return updates == null ? -1 : updates[0];
    }

    public int[] halfUpdates(Object[] objs, String colums[]) {
        if (objs == null || objs.length <= 0) {
            throw new RuntimeException("invalide update ,no data to apply!");
        }
        //clean the data ,remove the useless data
        List targets = new ArrayList();
        for (Object o : objs) {
            if (o != null) {
                targets.add(o);
            }
        }
        objs = targets.toArray();
        if (colums == null || colums.length <= 0) {
            return updates(objs);
        }

        String tableName = AnnotationParser.LoadAnnotationStructureStrategy(objs[0].getClass()).getTableName();
        String idColumName = AnnotationParser.LoadAnnotationStructureStrategy(objs[0].getClass()).getIdColumName();
        StringBuilder sql_halfUpdate = new StringBuilder("UPDATE " + tableName + " SET ");
        for (String colum : colums) {
            sql_halfUpdate.append(ConstantsKeeper.quotation_mark).append(colum).append(ConstantsKeeper.quotation_mark + " = ? ,");
        }
        sql_halfUpdate.deleteCharAt(sql_halfUpdate.length() - 1);
        sql_halfUpdate.append(" WHERE ").append(idColumName).append("=?");
        log.info("sqlHalfUpdate:" + sql_halfUpdate.toString());

        Field[] fields = objs[0].getClass().getDeclaredFields();
        //build the values arrays
        final Map metas[] = new Map[objs.length];
        int fieldIndex = 0;
        for (Object entity : objs) {
            metas[fieldIndex++] = ClassAnalysis.buildFieldsMap(fields, entity, true, colums);
        }
        log.info("the FieldMetaData:" + metas[0]);
        int[] updateCounts = getJdbcTemplate().batchUpdate(
                sql_halfUpdate.toString(),
                new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                log.info("the rowIndex:" + i);
                PreparedStatementBuilder.initPreparedStatement(metas[i], ps);
            }

            @Override
            public int getBatchSize() {
                return metas.length;
            }
        }
        );
        return updateCounts;
    }

    public void checkTableExist(Class clz) {
        if (clz == null) {
            return;
        }
        Field[] fields = clz.getDeclaredFields();
        MyTable myTable = (MyTable) clz.getAnnotation(MyTable.class);
        String tableName = AnnotationParser.LoadAnnotationStructureStrategy(clz).getTableName();

        SqlBuilder tableCreator = DialectHandlerSelector.selectTableCreator(DialectConfiguration.dbType);
        String sqlCreateTable = tableCreator.doCreateTable(tableName, myTable, fields);
        log.info("the sqlCreateTable is:" + sqlCreateTable);
        getJdbcTemplate().execute(sqlCreateTable);
    }

    private ResultHelp getScrollData(final Class clz, long firstindex, int maxresult, String[] colums, String whereSql, Object[] queryParams, int[] queryParamsTypes, Map orderby) {
        AnnotationStructureStrategy annotationStructureStrategy = AnnotationParser.LoadAnnotationStructureStrategy(clz);
        log.info("AnnotationStructureStrategy:" + annotationStructureStrategy);
        OrmObjectLoader objectLoader = null;
        if (annotationStructureStrategy.getFieldOneToOne() == null && annotationStructureStrategy.getFieldOneToMany() == null) {
            //load normal simple object,no orm
            objectLoader = new SimpleOrmObjectLoader();
        }
        if (annotationStructureStrategy.getFieldOneToOne() != null && annotationStructureStrategy.getFieldOneToMany() == null) {
            //one to one only
            objectLoader = new OneToOneOnlyOrmObjectLoader();
        }
        if (annotationStructureStrategy.getFieldOneToMany() != null && annotationStructureStrategy.getFieldOneToOne() == null) {
            //one to many only
            objectLoader = new OneToManyOnlyOrmObjectLoader();
        }
        if (annotationStructureStrategy.getFieldOneToOne() != null && annotationStructureStrategy.getFieldOneToMany() != null) {
            //both one to one and one to many
        }

        if (objectLoader == null) {
            throw new UnsupportedOperationException("Not supported yet. Because objectLoader is null"); //To change body of generated methods, choose Tools | Templates.            
        }
        ResultHelp rs = objectLoader.getScrollData(annotationStructureStrategy, getJdbcTemplate(), clz, firstindex, maxresult, colums, whereSql, queryParams, queryParamsTypes, orderby, myTableCacheService);
        if (rs == null) {
            return null;
        }
        String sqlCounter = "SELECT COUNT(" + annotationStructureStrategy.getIdColumName() + ") FROM " + annotationStructureStrategy.getTableName()
                + (whereSql == null || "".equals(whereSql.trim()) ? " " : " WHERE " + whereSql);
        rs.setTotalrecord(getJdbcTemplate().queryForObject(sqlCounter, queryParams, queryParamsTypes, Long.class));
        return rs;
    }

    public int halfUpdate(Object obj, String colums) {
        if (obj == null || colums == null || "".equals(colums)) {
            return -1;
        }
        int[] rs = halfUpdates(new Object[]{obj}, colums);
        return rs == null ? -1 : rs[0];
    }

    public int[] halfUpdates(Object[] objs, String colums) {
        if (objs == null || colums == null || "".equals(colums)) {
            return null;
        }
        return halfUpdates(objs, colums.split(","));
    }

    public long[] findIDs(Class clz, MyQueryCondition condition) {
        if (clz == null || condition == null) {
            return null;
        }
        final AnnotationStructureStrategy annotationStructureStrategy = AnnotationParser.LoadAnnotationStructureStrategy(clz);
        String sqlQueryIDs = "SELECT "
                + annotationStructureStrategy.getIdColumName()
                + " FROM " + annotationStructureStrategy.getTableName()
                + (condition.getWheresql() == null || "".equals(condition.getWheresql().trim()) ? " " : " WHERE " + condition.getWheresql().trim())
                + ((condition.getFirstindex() > -1 && condition.getMaxresult() > -1) ? (" LIMIT " + condition.getFirstindex() + ", " + condition.getMaxresult()) : "");
        log.info(sqlQueryIDs);
        if (condition.getQueryParamsNames() == null || condition.getQueryParamsNames().length <= 0) {
            if (condition.getQueryParamsTypes() != null) {
                return null;
            }
        }
        if (condition.getQueryParamsTypes() == null || condition.getQueryParamsTypes().length <= 0) {
            if (condition.getQueryParamsNames() != null) {
                return null;
            }
        }
        List ids = getJdbcTemplate().query(sqlQueryIDs, condition.getQueryParamsNames(), condition.getQueryParamsTypes(), new RowMapper() {
            public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getLong(annotationStructureStrategy.getIdColumName());
            }
        });
        long[] myids = new long[ids.size()];
        int counter = 0;
        for (Long thid : ids) {
            myids[counter++] = thid;
        }
        return myids;
    }

    public Object[] findByIds(Class clz, long[] theId) {
        AnnotationStructureStrategy annotationStructureStrategy = AnnotationParser.LoadAnnotationStructureStrategy(clz);
        StringBuilder where = new StringBuilder();
        where.append(" ").append(annotationStructureStrategy.getTableName()).append(".").append(annotationStructureStrategy.getIdColumName()).append(" IN(");
        for (long Id : theId) {
            where.append(Id).append(",");
        }
        where.deleteCharAt(where.length() - 1);
        where.append(")");
        Map orderby = new LinkedHashMap();
//        orderby.put("User.uid", "asc");
        orderby.put(annotationStructureStrategy.getTableName() + "." + annotationStructureStrategy.getIdColumName(), "asc");
        MyQueryCondition condition = new MyQueryCondition(-1, -1, null, where.toString(), null, null, orderby);
        ResultHelp rs = getScrollData(clz, condition.getFirstindex(), condition.getMaxresult(), condition.getColums(), condition.getWheresql(), condition.getQueryParamsNames(), condition.getQueryParamsTypes(), condition.getOrderby());
        if (rs == null) {
            return null;
        }
        return rs.getResultlist().toArray();
    }

}