olyanren
olyanren

Reputation: 1458

Injecting multiple dao into one service

if I have several DAOs to be injected into a Service that need to work together in a single transaction, how can I do this ?

@Component
public class CallerClass{
@Autowired    
private TransactionClass1 class1;
@Autowired    
private TransactionClass2 class2;

public void saveOperation(){    
    try{
        class1.save();
        class2.save();
    }catch(Exception ex){
    }
}
}

Like above simple codes. However, this code is lack

Upvotes: 1

Views: 2604

Answers (3)

Alex Barnes
Alex Barnes

Reputation: 7218

You would just inject all the DAOs in the same manner as you do normally i.e. setter or constructor using @Inject or @Autowired.

You then annotate your service method as Transactional and invoke the required operations on the multiple DAOs. The transaction will encompass all of the dao calls within it.

@Transactional
public void doStuff() {
  dao1.doStuff();
  dao2.doStuff();
}

Upvotes: 3

Ralph
Ralph

Reputation: 120771

You must open the transaction before you use the first dao (For example with @Transactional).

public class MyService{

  @Inject
  Dao1 dao1;

  @Inject
  Dao2 dao2;

  @Transactional
  public doStuffInOneTransaction{
     Object x = dao1.load();
     Object y = doSomething(x);
     dao2.save(y);
  }
}

Upvotes: 1

Nikola Yovchev
Nikola Yovchev

Reputation: 10206

Do you use JTA? Do you implement your transactions on your own? Please provide more information about your architecture so we can respond accordingly.

EDIT: Check this one out, for example: http://community.jboss.org/wiki/OpenSessionInView

Upvotes: 0

Related Questions