NutzCN Logo
问答 插入前用@Prev方法未执行 2.4.1.v20201014
发布于 1222天前 作者 Hamming 1631 次浏览 复制 上一个帖子 下一个帖子
标签:

以前可以 现在这么不行了呢

package io.nutz.nutzsite.common.base;

import io.nutz.nutzsite.module.sys.models.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.entity.annotation.*;
import org.nutz.lang.random.R;
import java.io.Serializable;
import java.util.Date;

/**
 * @author Hamming_Yu on 2018/12/29.
 */
public abstract class BaseModel implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column("create_by")
    @Comment("创建者")
    @Prev(els = @EL("$me.uid()"))
    @ColDefine(type = ColType.VARCHAR, width = 32)
    protected String createBy;

    @Column("create_time")
    @Prev(els = {@EL("$me.now()")})
    protected Date createTime;

    @Column("update_by")
    @Comment("更新者")
    @Prev(els = @EL("$me.uid()"))
    @ColDefine(type = ColType.VARCHAR, width = 32)
    protected String updateBy;

    @Prev(els=@EL("$me.now()"))
    @Column("update_time")
    protected Date updateTime;

    public String uuid() {
        return R.UU32().toLowerCase();
    }

    public String uid() {
        try {
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
            return user == null ? "" : user.getId();
        } catch (Exception e) {
            return "";
        }
    }

    public Date now() {
        return new Date();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }

    public String getUpdateBy() {
        return updateBy;
    }

    public void setUpdateBy(String updateBy) {
        this.updateBy = updateBy;
    }

}

[DEBUG] 17:29:52.617 net.sf.ehcache.store.disk.Segment.faultInternal(Segment.java:777) - fault added 0 on disk
[DEBUG] 17:29:52.618 org.nutz.plugins.cache.impl.lcache.LCache.fire(LCache.java:96) - fire channel=LCache:io.nutz.nutzsite.common.shiro.SimpleAuthorizingRealm.authorizationCache msg=u238it33c6j1opj986noqtk8ab:io.nutz.nutzsite.module.sys.models.User@57707421
[DEBUG] 17:29:52.621 org.nutz.plugins.cache.impl.lcache.CachePubSub.onPMessage(CachePubSub.java:15) - channel=LCache:io.nutz.nutzsite.common.shiro.SimpleAuthorizingRealm.authorizationCache, msg=u238it33c6j1opj986noqtk8ab:io.nutz.nutzsite.module.sys.models.User@57707421
[DEBUG] 17:29:52.625 org.nutz.dao.impl.sql.run.NutDaoExecutor.printSQL(NutDaoExecutor.java:391) - // NOT SQL // ElFieldMacro=uuid()
[DEBUG] 17:29:52.626 org.nutz.dao.impl.sql.run.NutDaoExecutor.printSQL(NutDaoExecutor.java:391) - INSERT INTO pro_product(id,title,url,price,weight,reference_url1,reference_url2,reference_url3,reference_url4,create_by,create_time,update_by,update_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) 
    |                                1 |    2 | 3 |    4 |    5 | 6 | 7 | 8 | 9 |   10 |   11 |   12 |   13 |
    |----------------------------------|------|--|------|------|--|--|--|--|------|------|------|------|
    | ed3aca6538754cd89979cac22fa12bf2 | test |  | NULL | NULL |  |  |  |  | NULL | NULL | NULL | NULL |
  For example:> "INSERT INTO pro_product(id,title,url,price,weight,reference_url1,reference_url2,reference_url3,reference_url4,create_by,create_time,update_by,update_time) VALUES('ed3aca6538754cd89979cac22fa12bf2','test','',NULL,NULL,'','','','',NULL,NULL,NULL,NULL) "
[DEBUG] 17:29:52.647 org.nutz.dao.impl.sql.run.NutDaoExecutor.printSQL(NutDaoExecutor.java:391) - // NOT SQL // ElFieldMacro=uuid()
[DEBUG] 17:29:52.648 org.nutz.dao.impl.sql.run.NutDaoExecutor.printSQL(NutDaoExecutor.java:391) - INSERT INTO sys_log(uu32,t,tg,url,src,msg,u_id,u_name,param,os,browser,ip,location,ct) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?) 
    |                                1 |         2 |  3 |                      4 |                                                                  5 |                                          6 |                          7 |     8 |                                                                                                                                            9 |       10 |       11 |              12 |   13 |                  14 |
    |----------------------------------|-----------|----|------------------------|--------------------------------------------------------------------|--------------------------------------------|----------------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------|----------|----------|-----------------|------|---------------------|
    | bd04c109a76648e3b444a0f7b9f03028 | aop.after | 商品 | /product/product/addDo | io.nutz.nutzsite.module.product.controller.ProductController#addDo | 新增保存商品 id=ed3aca6538754cd89979cac22fa12bf2 | 5a4eirrf16i83rta1og2l7qjl4 | admin | {"referenceUrl1":[""],"referenceUrl2":[""],"referenceUrl3":[""],"price":[""],"weight":[""],"title":["test"],"referenceUrl4":[""],"url":[""]} | Mac OS X | Chrome 8 | 0:0:0:0:0:0:0:1 | 内网IP | 2020-11-22 17:29:52 |
  For example:> "INSERT INTO sys_log(uu32,t,tg,url,src,msg,u_id,u_name,param,os,browser,ip,location,ct) VALUES('bd04c109a76648e3b444a0f7b9f03028','aop.after','商品','/product/product/addDo','io.nutz.nutzsite.module.product.controller.ProductController#addDo','新增保存商品 id=ed3aca6538754cd89979cac22fa12bf2','5a4eirrf16i83rta1og2l7qjl4','admin','{"referenceUrl1":[""],"referenceUrl2":[""],"referenceUrl3":[""],"price":[""],"weight":[""],"title":["test"],"referenceUrl4":[""],"url":[""]}','Mac OS X','Chrome 8','0:0:0:0:0:0:0:1','内网IP','2020-11-22 17:29:52') "
[DEBUG] 17:29:52.689 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:103) - Found mapping for [POST] path=/product/product/list : ProductController.list(ProductController.java:59)
[DEBUG] 17:29:52.692 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:166) - Get 'productController'<class io.nutz.nutzsite.module.product.controller.ProductController>
[DEBUG] 17:29:52.695 org.nutz.dao.impl.sql.run.NutDaoExecutor.printSQL(NutDaoExecutor.java:391) - SELECT * FROM sys_user  WHERE id=?

class 的能执行 继承后的 base 不执行 这个是为什么呢 求指点

@Table("pro_product")
public class Product extends BaseModel implements Serializable {
    private static final long serialVersionUID = 1L;

    @Name
    @Column("id")
    @Comment("id")
    @ColDefine(type = ColType.VARCHAR, width = 64)
    @Prev(els = {@EL("uuid()")})
    private String id;

23 回复

貌似没改过呀,debug看看?

@Prev 不会执行

main 方法 注解如下 是不是少了什么

@IocBean(create = "init", depose = "depose")
@IocBy(args={"*slog","*tx"})
@Localization(value = "locales/", defaultLocalizationKey = "zh-CN")
@ChainBy(type= MyActionChainMaker.class, args={})
public class MainLauncher {

EntityOperator 类 里面 方法 _fireEvent 什么都获取不到 是不是 因为 我自定义
动作练 导致的

    public List<Pojo> addInsert(Entity<?> en, Object obj) {
        if (null == en)
            return null;

        // 触发Pojo拦截器
        _fireEvent("prevInsert", obj, en);

        int len = Map.class.isAssignableFrom(obj.getClass()) ? 1 : Lang.eleSize(obj);
        List<Pojo> re = new ArrayList<Pojo>(len);
        if (len > 0) {
            if (len == 1) {
                for (Pojo pojo : en.cloneBeforeInsertMacroes())
                    re.add(pojo.setOperatingObject(obj));
            }
            re.add(dao.pojoMaker.makeInsert(en).setOperatingObject(obj));
            if (len == 1) {
                for (Pojo pojo : en.cloneAfterInsertMacroes())
                    re.add(pojo.setOperatingObject(obj));
            }
            pojoList.addAll(re);
        }
        return re;
    }

public class MyActionChainMaker implements ActionChainMaker {

    /**
     * 该接口只有一个方法
     * @param config
     * @param ai
     * @return
     */
    @Override
    public ActionChain eval(NutConfig config, ActionInfo ai) {
        // 提醒: config可以获取ioc等信息, ai可以获取方法上的各种配置及方法本身
        // 正常处理的列表
        List<Processor> list = new ArrayList<>();
        // 设置base/msg等内置属性
        list.add(new UpdateRequestAttributesProcessor());

        list.add(new GlobalsSettingProcessor());
        // 设置编码信息@Encoding
        list.add(new EncodingProcessor());
        // 获取入口类的对象,从ioc或直接new
        list.add(new ModuleProcessor());
        //shiro
        list.add(new NutShiroProcessor());
        // SQL 注入过滤 XSS过滤
        list.add(new XssSqlFilterProcessor());
        // 处理@Filters
        list.add(new ActionFiltersProcessor());
        // 处理@Adaptor
        list.add(new AdaptorProcessor());
        //必填项做判断
        list.add(new ValidationProcessor());
        // 执行入口方法
        list.add(new MethodInvokeProcessor());
        // 对入口方法进行渲染@Ok
        list.add(new ViewProcessor());
        for (Processor p : list) {
            try {
                p.init(config, ai);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        // 最后是专门负责兜底的异常处理器,这个处理器可以认为是全局异常处理器,对应@Fail
        ErrorProcessor error = new ErrorProcessor();
        try {
            error.init(config, ai);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return new NutActionChain(list, error, ai);
    }
}

为什么都会打印

[DEBUG] 20:38:45.613 org.nutz.dao.impl.sql.run.NutDaoExecutor.printSQL(NutDaoExecutor.java:391) - // NOT SQL // ElFieldMacro=uuid()

AnnotationEntityMaker 里面
的两个方法 断点都不执行

    private void _evalFieldMacro(Entity<?> en, List<MappingInfo> infos) {
        for (MappingInfo info : infos) {
            // '@Prev' : 预设值
            if (null != info.annPrev) {
                boolean flag = en.addBeforeInsertMacro(__macro(en.getField(info.name),
                                                _annToFieldMacroInfo(info.annPrev.els(),
                                                                     info.annPrev.value())));
                if (flag && null != info.annId && info.annId.auto()) {
                    log.debugf("Field(%s#%s) autoset as @Id(auto=false)", en.getType().getName(), info.name);
                    ((NutMappingField)en.getField(info.name)).setAutoIncreasement(false);
                }
            }

            // '@Next' : 后续获取
            if (null != info.annNext
                && en.addAfterInsertMacro(__macro(en.getField(info.name),
                                                  _annToFieldMacroInfo(info.annNext.els(),
                                                                       info.annNext.value())))) {
                continue;
            }
            // '@Id' : 的自动后续获取
            else if (null != info.annId && info.annId.auto() && en.getField(info.name).isAutoIncreasement()) {
            	if (!expert.isSupportAutoIncrement() || !expert.isSupportGeneratedKeys())
            		en.addAfterInsertMacro(expert.fetchPojoId(en, en.getField(info.name)));
            }
        }
    }

    private Pojo __macro(MappingField ef, List<FieldMacroInfo> infoList) {
        FieldMacroInfo theInfo = null;
        // 根据当前数据库,找到合适的宏
        for (FieldMacroInfo info : infoList) {
            if (DB.OTHER == info.getDb()) {
                theInfo = info;
            } else if (info.getDb().name().equalsIgnoreCase(expert.getDatabaseType())) {
                theInfo = info;
                break;
            }
        }
        // 如果找到,增加
        if (null != theInfo) {
            if (theInfo.isEl())
                return new ElFieldMacro(ef, theInfo.getValue());
            else
                return new SqlFieldMacro(ef, theInfo.getValue());
        }
        return null;
    }

改成老版本就正常吗? 或者写到当前类就正常吗?

获取注解信息的类是 AnnotationEntityMaker

换成 2.3.8.v20191031 还是不行

我要如何 分析 bug呢 正常 是执行 AnnotationEntityMaker 哪个方法呢

那看来是你自定义执行链的问题了...

哦 那么怎么加上呢

分两个问题:
1. 有没有读取到@Prev, 在 _annToFieldMacroInfo方法 和 ._evalFieldMacro 方法
2. 有没有执行@Prev, 在NutDaoExecutor之类的地方

我几乎可以肯定的是, 读取是没有问题的

有没有执行@Prev, 在NutDaoExecutor之类的地方
那 我再加个动作链吗

执行链 注释了 执行 还是 没有运行@Prev

fastInsert 不执行 @Prev 但会执行 @PrevInsert 和 @PrevUpdate
所以你看,budwk V6 都是使用后者。

我就是普通的Insert 我改成 PrevInsert 也不会执行

发我一个 git 版本号。
写一些测试试试
我刚刚解决过一个 filter的问题
可以帮你查一查这个问题。

沉了么 没有人 看看么

添加回复
请先登陆
回到顶部