java - EJB,Hibernate,当object.setProperty在服务中时自动保存

标签 java hibernate ejb autocommit

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

Controller -> 服务 -> 存储库 -> DB(oracle)。

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

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

我展示我的例子:

@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");
        }
    }


}

我的 Controller 调用我的服务。

@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);
    }
}

最佳答案

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

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

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

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

关于java - EJB,Hibernate,当object.setProperty在服务中时自动保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108597/

相关文章:

java - findViewById() 从 fragment 中返回 null - Android

java - 验证 JOptionPane.ShowInputDialog 中的用户输入

hibernate - jackson 双向关系(一对多)不起作用

mysql - org.hibernate.MappingException :Could not determine type for

java - Jboss (6.4 EAP) 到 WebSphere (7.x)

java - 本地方法调用中的 EJB 事务

java - 在Java中,为什么map.get(key)[0]作为左侧有效,而map.get(key)则无效?

java - hibernate java ORA-02292 : integrity constraint violated - child record found Course with Review

java - Atomikos:使用 PostgreSQL 时数据未保存

java - JBoss EAP 6.1 上的 Spring Data JPA - org.hibernate.StaleObjectStateException : Row was updated or deleted by another transaction