Hibernate 使用 findOne 和 findById 无法看到数据库中更新后触发器对记录

我在我的项目中使用 Spring boot 1.5.22、Spring data 和 Hibernate 5.2.18。当我使用 Dao 保存实体对象时:


platDao.save(plat);

数据库中正在执行 BEFORE INSERT 类型的触发器,该触发器正在数据库字段中插入多个文档。当我在数据库工具中使用 SQL 从数据库中的表中进行选择时,我可以看到该字段中的值。但是当我使用 hibernate 和 findOne 方法获取此记录时,我在此字段中看到 null:


Platnosc plat = platDao.findOne(platId);

我也尝试过这个:


Platnosc plat = platDao.findById(platId);

但结果是一样的,触发器设置的字段为空。


我的服务代码:


public List<Platnosc> createDocumentForInvoice(Integer fakturaId) {


    AuthUser user = loginMgr.getLoggedUser();


    Platnosc plat = Platnosc.builder()

            // I don't set field platnoscNr here it is null

            .build();


    platDao.save(plat);


    return plat;

}

我的控制器的代码:


public Response createDocumentForInvoice(

        @RequestParam(value = "fakturaId", required = true) Integer fakturaId) {


    List<Platnosc> platList = platMgr.createDocumentForInvoice(fakturaId);


    // after this I can see in database value of field platnoscNr which was inserted by trigger


    String platNr = platList.stream()

            .map(p -> {

                Platnosc plat = platDao.findById(p.getPlatnoscId());     

                return String.format("%s nr %s",

                        platMgr.getRodzajTextForPlatnoscRodzaj(plat.getPlatnoscRodzaj()),

                        plat.getPlatnoscNr());

            })

            .collect(Collectors.joining(", "));


    return Response.ok(platList.size() == 0

            ? "No document was created"

            : "Created documents: " + platNr)

            .build();

}

回应是:


“已创建的文档:信用卡编号为空,转账编号为空,其他付款编号为空”


慕后森
浏览 112回答 2
2回答

互换的青春

保存后刷新实体。

慕侠2389804

为了查看触发器所做的更改,我在 platDao.save(plat) 之后在服务中添加了两行代码:实体管理器.flush();EntityManager.flush() 操作可用于在提交事务之前将所有更改写入数据库。lush() 并不执行实际的提交。实体管理器.刷新(平台);EntityManager.refresh() 操作用于从数据库刷新对象的状态。刷新可用于恢复更改,或者如果您的 JPA 提供程序支持缓存,则可用于刷新过时的缓存数据。有时需要查询或查找操作刷新结果。现在我的代码看起来像这样:public List<Platnosc> createDocumentForInvoice(Integer fakturaId) {&nbsp; &nbsp;AuthUser user = loginMgr.getLoggedUser();&nbsp; &nbsp;Platnosc plat = Platnosc.builder()&nbsp; &nbsp; &nbsp; &nbsp; // I don't set field platnoscNr here it is null&nbsp; &nbsp; &nbsp; &nbsp; .build();&nbsp; &nbsp; platDao.save(plat);&nbsp; &nbsp; entityManager.flush();&nbsp; &nbsp; entityManager.refresh(plat);&nbsp; &nbsp; return plat;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java