org.zht.framework.service.impl.BaseServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for org.zht.framework.service.impl.BaseServiceImpl.java

Source

/**
 * Copyright (c) 2015 https://github.com/zhaohuatai
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.zht.framework.service.impl;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property;
//import org.hibernate.mapping.Table;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.Transactional;
import org.zht.framework.annos.CurrentTimeStamp;
import org.zht.framework.annos.TreeConstruct;
import org.zht.framework.annos.TreeParentFied;
import org.zht.framework.data.DataSet;
import org.zht.framework.data.POType;
import org.zht.framework.data.ParamObject;
import org.zht.framework.data.RowMap;
import org.zht.framework.exception.ServiceLogicalException;
import org.zht.framework.service.IBaseService;
import org.zht.framework.spring.SpringUtils;
import org.zht.framework.util.ZBeanUtil;
import org.zht.framework.util.ZStrUtil;
import org.zht.framework.zhtdao.base.impl.BaseDaoImpl;
import org.zht.framework.zhtdao.identity.PKBaseEntity;

import com.esotericsoftware.reflectasm.MethodAccess;

//@Service
@Transactional(rollbackFor = Exception.class)
@SuppressWarnings("hiding")
public class BaseServiceImpl<M extends PKBaseEntity> implements IBaseService<M> {
    @Resource(name = "baseDaoImpl")
    protected BaseDaoImpl baseDaoImpl;

    private LocalSessionFactoryBean factory = (LocalSessionFactoryBean) SpringUtils.getBean("&sessionFactory");

    private Class<? extends PKBaseEntity> entityClass;
    //????
    protected final PersistentClass clazz = factory.getConfiguration()
            .getClassMapping(this.getEntityClass().getName());
    //   protected final Table table = clazz.getTable(); 
    protected MethodAccess access = MethodAccess.get(this.getEntityClass());

    @SuppressWarnings("unchecked")
    public Class<?> getEntityClass() {
        Type type = getClass().getGenericSuperclass();
        if (entityClass == null) {
            entityClass = (Class<? extends PKBaseEntity>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }
        return entityClass;
    }

    @Override
    public void $base_saveOrUpdate(M m) {
        if (m == null) {
            throw new ServiceLogicalException("????");
        }
        if (m.getId() != null) {
            $base_update(m);
        } else {
            $base_save(m);
        }
    }

    //---------------------------------------------$$base_add------S-----------------------------------------------------
    @Override
    public void $base_save(M m) {
        if (m == null) {
            throw new ServiceLogicalException("????");
        }
        //------------------???-------------------------------------
        //?????? ,,?hibernate?**************
        String checkNotNullRes = checkNotNull(m);//?????? 
        if (checkNotNullRes != null) {
            throw new ServiceLogicalException(checkNotNullRes);
        }
        //
        String checkLenth = checkLenth(m);//
        if (checkLenth != null) {
            throw new ServiceLogicalException(checkLenth);
        }
        //-----------------------------------------------------------------------
        //??
        String isMultiTreeRoot = checkIsMultiTreeRootForAddNew(m);
        if (isMultiTreeRoot != null) {
            throw new ServiceLogicalException(isMultiTreeRoot);
        }
        String checkUniqueRes = checkUnique(m);
        if (checkUniqueRes != null) {
            throw new ServiceLogicalException(checkUniqueRes);
        }
        generateCurrentTimeStamp(m);
        baseDaoImpl.saveOrUpdate(m);
    }

    //---------------------------------------------$$base_add------E-----------------------------------------------------   
    //---------------------------------------------$base_update------S-----------------------------------------------------    
    @SuppressWarnings("unchecked")
    @Override
    public void $base_update(M m) {
        if (m == null || m.getId() == null) {
            throw new ServiceLogicalException("????");
        }
        //------------------???-------------------------------------
        //?
        String checkNotNullRes = checkNotNull(m);//?????? 
        if (checkNotNullRes != null) {
            throw new ServiceLogicalException(checkNotNullRes);
        }
        //
        String checkLenth = checkLenth(m);//
        if (checkLenth != null) {
            throw new ServiceLogicalException(checkLenth);
        }
        //-------------------------------------------------------

        //
        String checkParentRes = checkParentNodeIfTree(m);
        if (checkParentRes != null) {
            throw new ServiceLogicalException(checkParentRes);
        }
        //
        String checkUniqueRes = checkUnique(m);
        if (checkUniqueRes != null) {
            throw new ServiceLogicalException(checkUniqueRes);
        }
        generateCurrentTimeStamp(m);
        M temp = (M) baseDaoImpl.find(this.getEntityClass(), m.getId());//?id  ?
        ZBeanUtil.copy(m, temp, true);//?
        baseDaoImpl.saveOrUpdate(temp);
    }
    //---------------------------------------------$base_update------E-----------------------------------------------------    

    //----------------------------------------------$base_delete$Just------S---------------------------------------------------------------------   
    @Override
    public void $base_delete$Just(M m) {
        if (m == null || m.getId() == null) {
            throw new ServiceLogicalException("??");
        }
        baseDaoImpl.delete(this.getEntityClass(), m.getId());
    }

    @Override
    public void $base_delete$Just(Serializable id) {
        if (id == null) {
            throw new ServiceLogicalException("??");
        }
        baseDaoImpl.delete(this.getEntityClass(), id);
    }

    @Override
    public void $base_deleteByIdsInCase$Just(Serializable[] ids) {
        if (ids == null || ids.length == 0) {
            throw new ServiceLogicalException("??");
        }
        if (ids != null && ids.length > 0) {
            baseDaoImpl.deleteByIdsInCase(this.getEntityClass(), ids);
        }
    }

    @Override
    public void deleteAll() {
        baseDaoImpl.deleteAll(this.getEntityClass());
    }

    //----------------------------------------------$base_delete$Just-------------E--------------------------------------------------------------
    //----------------------------------------------$base_find------------s--------------------------------------------------------------
    @SuppressWarnings("unchecked")
    @Override
    public <M> M $base_find(Serializable id) {
        return (M) baseDaoImpl.find(this.getEntityClass(), id);
    }

    @Override
    public Long $base_findTotalCount() {
        return baseDaoImpl.findTotalCount(this.getEntityClass());
    }

    @SuppressWarnings("unchecked")
    @Override
    public <M> List<M> $base_findAll() {
        return (List<M>) baseDaoImpl.findAll(this.getEntityClass());
    }

    @SuppressWarnings("unchecked")
    @Override
    public <M> List<M> $base_findByIdsInCase(Serializable[] ids) {
        if (ids != null && ids.length == 0) {
            return null;
        }
        return (List<M>) baseDaoImpl.findByIdsInCase(this.getEntityClass(), ids);
    }

    @Override
    public DataSet $base_loadDataSetFromOneEntity(ParamObject paramObject, RowMap rowMap) {
        return baseDaoImpl.loadDataSetFromOneEntity(this.getEntityClass(), paramObject, rowMap);
    }

    @Override
    public DataSet $base_loadDataSetFromOneEntity(ParamObject paramObject, RowMap rowMap, String extraCondition) {
        return baseDaoImpl.loadDataSetFromOneEntity(this.getEntityClass(), paramObject, rowMap, extraCondition);
    }

    @Override
    @SuppressWarnings({ "unchecked" })
    public <M> List<M> $base_findListByParamObject(ParamObject paramObject, String extraSQLStr) {
        return (List<M>) baseDaoImpl.findListByParamObject(this.getEntityClass(), paramObject, extraSQLStr);
    }

    @Override
    public Long $base_findCountByParamObject(ParamObject paramObject, String extraSQLStr) {
        return baseDaoImpl.findCountByParamObject(this.getEntityClass(), paramObject, extraSQLStr);
    }

    //----------------------------------------------$base_find$Just-------------E--------------------------------------------------------------
    private String checkLenth(M m) {
        // final PersistentClass clazz = factory.getConfiguration().getClassMapping(m.getClass().getName()); 
        if (clazz == null) {
            throw new ServiceLogicalException("[]???");
        }
        // final Table table = clazz.getTable(); 
        //          if(table==null){
        //             throw new ServiceLogicalException("[]???");
        //          }
        @SuppressWarnings("unchecked")
        final Iterator<Property> iterator = clazz.getPropertyIterator();
        if (iterator == null) {
            throw new ServiceLogicalException(
                    "[]???");
        }
        // MethodAccess access = MethodAccess.get(m.getClass());
        while (iterator.hasNext()) {
            Property property = iterator.next();
            if ("id".equals(property.getName())) {
                continue;
            }
            Iterator<?> columnIterator = property.getColumnIterator();
            if (columnIterator.hasNext()) {
                Column column = (Column) columnIterator.next();
                int lenth = column.getLength();
                Object value = (Object) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(property.getName()));
                if (value != null) {
                    if (value instanceof java.lang.String) {
                        if (lenth < (((java.lang.String) value).length())) {
                            return (" [" + property.getName() + "] ??");
                        }

                    }
                }
            }
        }
        return null;
    }

    private String checkNotNull(M m) {
        // final PersistentClass clazz = factory.getConfiguration().getClassMapping(m.getClass().getName()); 
        if (clazz == null) {
            throw new ServiceLogicalException("[]???");
        }
        //final Table table = clazz.getTable(); 
        //          if(table==null){
        //             throw new ServiceLogicalException("[]???");
        //          }
        @SuppressWarnings("unchecked")
        final Iterator<Property> iterator = clazz.getPropertyIterator();
        if (iterator == null) {
            throw new ServiceLogicalException(
                    "[]???");
        }
        // MethodAccess access = MethodAccess.get(m.getClass());
        while (iterator.hasNext()) {
            Property property = iterator.next();
            if ("id".equals(property.getName())) {
                continue;
            }
            Iterator<?> columnIterator = property.getColumnIterator();
            if (columnIterator.hasNext()) {
                Column column = (Column) columnIterator.next();
                if (!column.isNullable()) {

                    Object value = (Object) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(property.getName()));
                    //System.out.println(property.getName()+" "+value);
                    if (ZStrUtil.trimToNullIfStr(value) == null) {
                        return (" [" + property.getName() + "] ?");
                    }

                }
            }
        }
        return null;
    }

    private String checkUnique(M m) {
        //          final PersistentClass clazz = factory.getConfiguration().getClassMapping(m.getClass().getName()); 
        if (clazz == null) {
            throw new ServiceLogicalException("[]???");
        }
        // final Table table = clazz.getTable(); 
        //          if(table==null){
        //             throw new ServiceLogicalException("[]???");
        //          }
        @SuppressWarnings("unchecked")
        final Iterator<Property> iterator = clazz.getPropertyIterator();
        if (iterator == null) {
            throw new ServiceLogicalException(
                    "[]???");
        }
        //MethodAccess access = MethodAccess.get(m.getClass());
        while (iterator.hasNext()) {
            Property property = iterator.next();
            if ("id".equals(property.getName())) {
                continue;
            }
            Iterator<?> columnIterator = property.getColumnIterator();
            if (columnIterator.hasNext()) {
                Column column = (Column) columnIterator.next();
                if (column.isUnique()) {

                    Object value = (Object) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(property.getName()));
                    //System.out.println(property.getName()+" "+value);
                    Object id = baseDaoImpl.findIdByUnique(m.getClass(), property.getName(), value);
                    if (id != null && !id.equals(m.getId())) {
                        return ("?[" + value + "]?");
                    }
                }
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private String checkIsMultiTreeRootForAddNew(M m) {
        //??
        if (m.getClass().isAnnotationPresent(TreeConstruct.class)) {
            String parentPropertyName = getParentPropertyName(m);
            if (parentPropertyName == null || parentPropertyName.isEmpty()) {
                return ("???");
            }
            //MethodAccess access = MethodAccess.get(this.getEntityClass());
            M parent = (M) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(parentPropertyName));
            if (parent == null || parent.getId() == null) {//,??
                List<Long> rootlist = (List<Long>) baseDaoImpl.findJustList(" select id from "
                        + m.getClass().getName() + " where " + parentPropertyName + ".id is null",
                        new ParamObject(POType.H_NO_NC));
                if (rootlist != null && rootlist.size() > 1) {
                    return ("????");
                }
                if (rootlist != null && rootlist.size() > 0) {
                    return ("???");
                }
            }
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private String checkParentNodeIfTree(M m) {
        //
        if (m.getClass().isAnnotationPresent(TreeConstruct.class)) {
            String parentPropertyName = getParentPropertyName(m);
            if (parentPropertyName == null || parentPropertyName.isEmpty()) {
                throw new ServiceLogicalException(
                        "??");
            }

            //MethodAccess access = MethodAccess.get(m.getClass());
            M parent = (M) access.invoke(m, "get" + ZStrUtil.toUpCaseFirst(parentPropertyName));
            if (parent != null && parent.getId() != null) {//?
                Object pid = baseDaoImpl.findIdByUnique(m.getClass(), "id", parent.getId());
                if (pid == null) {
                    return ("?");
                }
                if (pid != null && pid.equals(m.getId())) {
                    return ("?");
                }
                while (!(parent == null || parent.getId() == null)) {
                    pid = baseDaoImpl.findParentIdBySelfUnique(m.getClass(), parentPropertyName, "id", pid);
                    if (pid == null) {
                        break;
                    }
                    if (m.getId().equals(pid) || m.getId() == pid) {
                        return ("??");
                    }
                }
            } else {//,,
                List<Long> rootlist = (List<Long>) baseDaoImpl.findJustList(" select id from "
                        + m.getClass().getName() + " where " + parentPropertyName + ".id is null",
                        new ParamObject(POType.H_NO_NC));
                if (rootlist != null && rootlist.size() > 1) {
                    return ("????");
                }
                if (rootlist != null && rootlist.size() > 0) {
                    if (!rootlist.get(0).equals(m.getId())) {
                        return ("???");
                    }
                }
            }
        }
        return null;
    }

    private String getParentPropertyName(M m) {
        Field[] fields = m.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return null;
        }
        for (Field f : fields) {
            if (f.isAnnotationPresent(TreeParentFied.class)) {
                return f.getName();
            }
        }
        return null;
    }

    private void generateCurrentTimeStamp(M m) {
        Field[] fields = m.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return;
        }
        for (Field f : fields) {
            if (f.isAnnotationPresent(CurrentTimeStamp.class)) {
                MethodAccess access = MethodAccess.get(m.getClass());
                access.invoke(m, "set" + ZStrUtil.toUpCaseFirst(f.getName()), new Date(System.currentTimeMillis()));
            }
        }
    }
}