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

com.mycomm.dao.dao4comm.framework.impl.OneToOneOnlyOrmObjectLoader 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.framework.impl;

import com.mycomm.IProtocol.cache.TableCacheService;
import com.mycomm.IProtocol.sql.annotation.MyOneToOne;
import com.mycomm.dao.dao4comm.ResultHelp;
import com.mycomm.dao.dao4comm.framework.AnnotationStructureStrategy;
import com.mycomm.dao.dao4comm.framework.OrmObjectLoader;
import com.mycomm.dao.dao4comm.util.AnnotationParser;
import com.mycomm.dao.dao4comm.util.InstanceBuilder;
import com.mycomm.dao.dao4comm.util.Utils;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author jw362j
 */
public class OneToOneOnlyOrmObjectLoader implements OrmObjectLoader {

    private static final Logger log = LoggerFactory.getLogger(OneToOneOnlyOrmObjectLoader.class);

    /**
     * SELECT User.uid ,User.userName ,User.age,Address.*,AnnoTest.* FROM
     * User,Address,AnnoTest WHERE (User.userName = 'zhangsan' and User.age = 58
     * ) and (User.uid = Address.uid) group by user.uid ORDER BY User.uid
     * asc,User.age desc LIMIT 0, 300; SELECT User.uid ,User.userName
     * ,User.age,Address.*,AnnoTest.* FROM User,Address,AnnoTest WHERE User.sex
     * = ? and User.age = ? and (User.uid = Address.uid) ORDER BY User.aid
     * asc,User.city desc LIMIT 0, 3
     *
     * @param annotationStructureStrategy
     * @param jdbcTemplate
     * @param clz
     * @param firstindex
     * @param maxresult
     * @param colums
     * @param whereSql
     * @param queryParams
     * @param queryParamsTypes
     * @param orderby
     * @return
     */
    public ResultHelp getScrollData(final AnnotationStructureStrategy annotationStructureStrategy, JdbcTemplate jdbcTemplate, final Class clz, long firstindex, int maxresult, String[] colums, String whereSql, Object[] queryParams, int[] queryParamsTypes, Map orderby,TableCacheService myTableCacheService) {
        if (jdbcTemplate == null) {
            throw new RuntimeException("JdbcTemplate is null ,game over!");
        }
        String primaryTableName = AnnotationParser.LoadAnnotationStructureStrategy(clz).getTableName();
        final Field[] fields = annotationStructureStrategy.getFieldOneToOne();
        String meppedBy[] = new String[fields.length];
        AnnotationStructureStrategy subTableNames[] = new AnnotationStructureStrategy[fields.length];
        int flag = 0;
        log.info("the primaryTableName:" + primaryTableName);
        for (Field field : fields) {
            Class fieldClz = field.getType();
            if (field.isAnnotationPresent(MyOneToOne.class)) {
                MyOneToOne theColum = (MyOneToOne) field.getAnnotation(MyOneToOne.class);
                String mBy = theColum.mappedBy();
                if ("".equals(mBy) || mBy == null) {
                    mBy = annotationStructureStrategy.getIdColumName();
                }
                meppedBy[flag] = mBy;
            }
            AnnotationStructureStrategy subField = AnnotationParser.LoadAnnotationStructureStrategy(fieldClz);
            subTableNames[flag++] = subField;
        }

        StringBuilder sbColums = new StringBuilder();
        for (AnnotationStructureStrategy tName : subTableNames) {
            sbColums.append(tName.getTableName()).append(".*,");
        }
        sbColums.deleteCharAt(sbColums.length() - 1);

        StringBuilder sbFromTables = new StringBuilder();
        for (AnnotationStructureStrategy tName : subTableNames) {
            sbFromTables.append(tName.getTableName()).append(",");
        }
        sbFromTables.deleteCharAt(sbFromTables.length() - 1);
        StringBuilder syntaxWhere = new StringBuilder();
        short syntaxWhereFlag = 0;
        for (AnnotationStructureStrategy subT : subTableNames) {
//            String mappedBy = subT.ge\\
            if (syntaxWhereFlag == (subTableNames.length - 1)) {
                syntaxWhere.append(primaryTableName).append(".").append(annotationStructureStrategy.getIdColumName()).append("=").append(subT.getTableName()).append(".").append(meppedBy[syntaxWhereFlag]);
            } else {
                syntaxWhere.append(primaryTableName).append(".").append(annotationStructureStrategy.getIdColumName()).append("=").append(subT.getTableName()).append(".").append(meppedBy[syntaxWhereFlag]).append(" or ");
            }
            syntaxWhereFlag++;
        }

        String sqlQuery = "SELECT "
                + ((colums != null && colums.length > 0) ? Utils.buildProjectionWithTableName(primaryTableName, colums) + "," + sbColums.toString() : " " + primaryTableName + ".* ," + sbColums.toString())
                + " FROM " + annotationStructureStrategy.getTableName() + (" ," + sbFromTables.toString())
                + (whereSql == null || "".equals(whereSql.trim()) ? " WHERE (" + syntaxWhere.toString() + ") " : " WHERE " + whereSql + " AND (" + syntaxWhere.toString() + ") ")
                + (" GROUP BY " + primaryTableName + "." + annotationStructureStrategy.getIdColumName())
                + Utils.buildOrderby(orderby)
                + ((firstindex > -1 && maxresult > -1) ? (" LIMIT " + firstindex + ", " + maxresult) : "");
        log.info(sqlQuery);
        if (queryParams == null || queryParams.length <= 0) {
            if (queryParamsTypes != null) {
                return null;
            }
        }
        if (queryParamsTypes == null || queryParamsTypes.length <= 0) {
            if (queryParams != null) {
                return null;
            }
        }
        //build the SQL done,start to load data

        List queryResult;
        queryResult = jdbcTemplate.query(sqlQuery, queryParams, queryParamsTypes, new RowMapper() {
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                try {
                    /*
                    log.info("==================================================");
                    log.info("the value(User.uid):" + rs.getInt("uid"));
                    log.info("the value(User.userName):" + rs.getString("userName"));
                    log.info("the value(User.age):" + rs.getInt("age"));
                    log.info("the value(User.aid):" + rs.getInt("aid"));
                    log.info("the value(state):" + rs.getString("state"));
                    log.info("the value(city):" + rs.getString("city"));
                    log.info("the value(town):" + rs.getString("town"));
                    log.info("the value(theName):" + rs.getString("theName"));
                    log.info("the value(sex):" + rs.getBoolean("sex"));
                    log.info("the value(b):" + rs.getByte("b"));
                    log.info("the value(s):" + rs.getShort("s"));
                    log.info("the value(f):" + rs.getFloat("f"));
                    log.info("the value(d):" + rs.getDouble("d"));
                    log.info("the value(date):" + rs.getTimestamp("de"));
                    log.info("==================================================");
                     */
                    Object instance = clz.newInstance();
                    InstanceBuilder.buildInstance(rs, instance, clz.getDeclaredFields(), annotationStructureStrategy.getIdColumName());
                    //build the properties for instance to finish one to one 
                    for (Field f : fields) {
                        // Field[] fs = subFieldInstance.getClass().getDeclaredFields();
                        Class class_f = f.getType();
                        Object instance_f = class_f.newInstance();
                        log.info("instance_f:" + instance_f + ",class_f" + class_f);
                        InstanceBuilder.buildInstance(rs, instance_f, instance_f.getClass().getDeclaredFields(), AnnotationParser.LoadAnnotationStructureStrategy(instance_f.getClass()).getIdColumName());
                        f.set(instance, instance_f);
                    }
                    return instance;
                } catch (InstantiationException ex) {
                    log.error(ex.getMessage());
                    return null;
                } catch (IllegalAccessException ex) {
                    log.error(ex.getMessage());
                    return null;
                }
            }
        });

        ResultHelp qr = new ResultHelp();
        qr.setResultlist(queryResult);
        return qr;
    }

}