Using stateless EJB beans in an Entity Bean
Asked Answered
V

2

6

Obviously using stateless EJB beans in an entity bean smells, but please consider a scenario as follows and tell me if you know of a better solution:

  1. I have an InvoiceTemplate Entity Bean with field NextInvoiceDate
  2. Generating NextInvoiceDate is a complex procedure and should be performed outside of the InvoiceTemplate class
  3. NextInvoiceDate should be updated each time InvoiceTemplate is stored to the db

For now I have logic regarding the generation of NextInvoiceDate in @PrePersist @PreUpdate methon in InvoiceTemplate entity bean. The logic is getting more and more complicated and I want to move it outside of the InvoiceTemplate entity bean. It looks to me that there should be a service to calculate NextInvoiceDate. But then is it right to invoke this service from the inside of InvoiceTemplate?

Verso answered 13/9, 2010 at 11:13 Comment(1)
is it an entity-bean (EJB 2.0) or a JPA entity?Trimolecular
T
3

It isn't such a smell - it is a lean towards domain-driven design.

I don't know of any way to do this automatically, but you can:

  • in the session beans where you handle your Invoicetemplate, inject the helper bean that has the logic to calculate the next date
  • create a private field with a setter on the entity, and before you start using it call entity.setNextDateHelper(..)

You can also check whether AspectJ doesn't offer some EJB options so that you can inject the EJB whenever an entity of a given type (InvoiceTemplate) is created. AspectJ works like that with spring beans, I don't know whether there are such options for EJB.

Trimolecular answered 13/9, 2010 at 11:51 Comment(1)
Well said. +1 just for the first sentence.Randolf
R
0

Do you need anything as complicated as a service or EJB? Can you just write a static method (possibly on a utility class) to hold the logic? Normally I'm pretty biased against this sort of thing, but if all you've got is some complex logic that doesn't require any DB interaction or a lot of object collaboration, it may be the cleanest approach.

Revel answered 13/9, 2010 at 13:15 Comment(3)
Testing would be hurt in this way.Verso
Well, what if it does require DB interaction and a lot of object collaboration?Alidia
If it does, then you're probably back to a service or EJB again, so you can participate in transactions or share context. Which brings you back to timing issues, coordination and dependencies.Revel

© 2022 - 2024 — McMap. All rights reserved.