gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:55:42 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com