【问题标题】:EJB, Hibernate, auto save when object.setProperty in serviceEJB,休眠,当 object.setProperty 服务时自动保存
【发布时间】:2014-04-16 11:50:05
【问题描述】:

在我的项目中,我有这样的架构:

控制器 -> 服务 -> 存储库 -> 数据库(oracle)。

  1. 控制器 -> 查看规则
  2. 服务 -> 业务规则
  3. 存储库 -> 数据库规则。

当我在服务中更改对象的 de 属性时,我的项目会自动执行更新。这是错误的,因为我必须调用我的存储库来保存!!!

我举个例子:

@RequestScoped @ApplicationScoped
public class HomeController { //this is my controller

    private List<Banner> banners;

        @EJB
    private IBannerService bannerService;

        @PostConstruct
    public void init() {
        try {
            this.banners = this.bannerService.buscarBanners(TipoBanner.HOME);
        } catch (Exception e) {
            e.printStackTrace();
            loggerApp(ModuloTipo.PORTAL, LogTipo.ERROR, getNomeUsuarioLogado(), PortalAcaoLog.INIT_ERRO, "erro ao abrir home");
        }
    }


}

我的控制器调用我的服务。

@Stateless(name = "BannerService")
@Remote(IBannerService.class)
public class BannerService implements IBannerService { //this is my service

    @EJB
    private IBannerRepository bannerRepository;

    @Override
    public List<Banner> buscarBanners(TipoBanner tipo) {
              List<Banner> bannersLink = this.bannerRepository.buscarBanners(tipo);

        for(Banner b : bannersLink) {
            System.out.println(b.getDescricao());
            b.setDescricao(b.getDescricao() + " - this is a test"); //when i do this, automatically save my object 0.o... i don`t now what is happening.
        }
        return bannersLink;
    }

        @Override
    public void salvar(Banner banner) {
        this.bannerRepository.update(banner); //when i want to save, i call this method
    }
}

这是我的存储库:

@Stateless(name = "BannerRepository")
@Local(IBannerRepository.class)
public class BannerRepository implements IBannerRepository {

        @PersistenceContext
    private EntityManager entityManager;

       @Override
    public void update(Object object) {
        this.entityManager.merge(object);
    }
}

【问题讨论】:

    标签: java hibernate ejb autocommit


    【解决方案1】:

    JPA EntityManager 的默认行为是在它参与的任何事务结束时刷新和提交 - 无论是普通的 PersistenceContext(您的情况)还是扩展的。

    此外,EJB 的默认行为是在所有公共方法上都是事务性的(需要传播),这意味着如果一个事务不存在,它将创建一个事务。

    您的属性更改每次都会提交,因为您的 BannerService 上每次都有一个事务(它是一个 EJB)。

    我建议在 BannerService 上使用 @TransactionAttribute(TransactionAttributeType.SUPPORTS) 注释 buscarBanners() 方法

    【讨论】:

    • 非常感谢柳永。这解决了我的问题。我将更多地研究@TransactionAttribute
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2011-12-16
    • 2019-08-23
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    相关资源
    最近更新 更多