In my project i have this architecture:
Controller -> Service -> Repository -> DB(oracle).
When i change de attribute of my object in Service, my project execute update automatically. This is wrong, because i have to call my repository to save!!!
I show my example:
@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");
}
}
}
My Controller calls my Service.
@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
}
}
And this is my repository:
@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);
}
}
The default behavior for a JPA EntityManager is to flush and commit in the end of any transaction it participates - being it a normal PersistenceContext (your case) or an extended one.
Also, the default behavior for an EJB is to be transactional on all public methods (with propagation REQUIRED), meaning it will create a transaction if one does not exists.
Your property changes are committed every time because there's a transaction every time on your BannerService (it's an EJB).
I would suggest annotating the buscarBanners() method on BannerService with @TransactionAttribute(TransactionAttributeType.SUPPORTS)